bash에서 스트링과 연관된 작업을 할 수 있다.

예를 들어, 스트링에서 특정 스트링을 감산한다거나. 또는 패턴을 이용하여 먼 일을 하고 싶을 때, 다음의 문서를 참고하면 된다.

 

 출처 :

http://tldp.org/LDP/abs/html/parameter-substitution.html

 

 

 

9.3. Parameter Substitution

Manipulating and/or expanding variables

${parameter}

Same as $parameter, i.e., value of the variable parameter. In certain contexts, only the less ambiguous ${parameter} form works.

May be used for concatenating variables with strings.

your_id=${USER}-on-${HOSTNAME}
echo "$your_id"
#
echo "Old \$PATH = $PATH"
PATH=${PATH}:/opt/bin  #Add /opt/bin to $PATH for duration of script.
echo "New \$PATH = $PATH"

${parameter-default}, ${parameter:-default}

If parameter not set, use default.

echo ${username-`whoami`}
# Echoes the result of `whoami`, if variable $username is still unset.

${parameter-default} and ${parameter:-default} are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null.

#!/bin/bash
# param-sub.sh

#  Whether a variable has been declared
#+ affects triggering of the default option
#+ even if the variable is null.

username0=
echo "username0 has been declared, but is set to null."
echo "username0 = ${username0-`whoami`}"
# Will not echo.

echo

echo username1 has not been declared.
echo "username1 = ${username1-`whoami`}"
# Will echo.

username2=
echo "username2 has been declared, but is set to null."
echo "username2 = ${username2:-`whoami`}"
#                            ^
# Will echo because of :- rather than just - in condition test.
# Compare to first instance, above.


#

# Once again:

variable=
# variable has been declared, but is set to null.

echo "${variable-0}"    # (no output)
echo "${variable:-1}"   # 1
#               ^

unset variable

echo "${variable-2}"    # 2
echo "${variable:-3}"   # 3

exit 0

The default parameter construct finds use in providing "missing" command-line arguments in scripts.

DEFAULT_FILENAME=generic.data
filename=${1:-$DEFAULT_FILENAME}
#  If not otherwise specified, the following command block operates
#+ on the file "generic.data".
#
#  Commands follow.

See also Example 3-4, Example 28-2, and Example A-6.

Compare this method with using an and list to supply a default command-line argument.

${parameter=default}, ${parameter:=default}

If parameter not set, set it to default.

Both forms nearly equivalent. The : makes a difference only when $parameter has been declared and is null, [1] as above.

echo ${username=`whoami`}
# Variable "username" is now set to `whoami`.

${parameter+alt_value}, ${parameter:+alt_value}

If parameter set, use alt_value, else use null string.

Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null, see below.

echo "###### \${parameter+alt_value} ########"
echo

a=${param1+xyz}
echo "a = $a"      # a =

param2=
a=${param2+xyz}
echo "a = $a"      # a = xyz

param3=123
a=${param3+xyz}
echo "a = $a"      # a = xyz

echo
echo "###### \${parameter:+alt_value} ########"
echo

a=${param4:+xyz}
echo "a = $a"      # a =

param5=
a=${param5:+xyz}
echo "a = $a"      # a =
# Different result from   a=${param5+xyz}

param6=123
a=${param6:+xyz}
echo "a = $a"      # a = xyz

${parameter?err_msg}, ${parameter:?err_msg}

If parameter set, use it, else print err_msg.

Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null, as above.

Example 9-15. Using parameter substitution and error messages

#!/bin/bash

#  Check some of the system's environmental variables.
#  This is good preventative maintenance.
#  If, for example, $USER, the name of the person at the console, is not set,
#+ the machine will not recognize you.

: ${HOSTNAME?} ${USER?} ${HOME?} ${MAIL?}
  echo
  echo "Name of the machine is $HOSTNAME."
  echo "You are $USER."
  echo "Your home directory is $HOME."
  echo "Your mail INBOX is located in $MAIL."
  echo
  echo "If you are reading this message,"
  echo "critical environmental variables have been set."
  echo
  echo

# ------------------------------------------------------

#  The ${variablename?} construction can also check
#+ for variables set within the script.

ThisVariable=Value-of-ThisVariable
#  Note, by the way, that string variables may be set
#+ to characters disallowed in their names.
: ${ThisVariable?}
echo "Value of ThisVariable is $ThisVariable".
echo
echo


: ${ZZXy23AB?"ZZXy23AB has not been set."}
#  If ZZXy23AB has not been set,
#+ then the script terminates with an error message.

# You can specify the error message.
# : ${variablename?"ERROR MESSAGE"}


# Same result with:    dummy_variable=${ZZXy23AB?}
#                      dummy_variable=${ZZXy23AB?"ZXy23AB has not been set."}
#
#                      echo ${ZZXy23AB?} >/dev/null

#  Compare these methods of checking whether a variable has been set
#+ with "set -u" . . .



echo "You will not see this message, because script already terminated."

HERE=0
exit $HERE   # Will NOT exit here.

# In fact, this script will return an exit status (echo $?) of 1.

Example 9-16. Parameter substitution and "usage" messages

#!/bin/bash
# usage-message.sh

: ${1?"Usage: $0 ARGUMENT"}
#  Script exits here if command-line parameter absent,
#+ with following error message.
#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT

echo "These two lines echo only if command-line parameter given."
echo "command line parameter = \"$1\""

exit 0  # Will exit here only if command-line parameter present.

# Check the exit status, both with and without command-line parameter.
# If command-line parameter present, then "$?" is 0.
# If not, then "$?" is 1.

Parameter substitution and/or expansion. The following expressions are the complement to the match in expr string operations (see Example 15-9). These particular ones are used mostly in parsing file path names.

Variable length / Substring removal

${#var}

String length (number of characters in $var). For an array, ${#array} is the length of the first element in the array.

Exceptions:

  • ${#*} and ${#@} give the number of positional parameters.

  • For an array, ${#array[*]} and ${#array[@]} give the number of elements in the array.

Example 9-17. Length of a variable

#!/bin/bash
# length.sh

E_NO_ARGS=65

if [ $# -eq 0 ]  # Must have command-line args to demo script.
then
  echo "Please invoke this script with one or more command-line arguments."
  exit $E_NO_ARGS
fi  

var01=abcdEFGH28ij
echo "var01 = ${var01}"
echo "Length of var01 = ${#var01}"
# Now, let's try embedding a space.
var02="abcd EFGH28ij"
echo "var02 = ${var02}"
echo "Length of var02 = ${#var02}"

echo "Number of command-line arguments passed to script = ${#@}"
echo "Number of command-line arguments passed to script = ${#*}"

exit 0
${var#Pattern}, ${var##Pattern}

${var#Pattern} Remove from $var the shortest part of $Pattern that matches the front end of $var.

${var##Pattern} Remove from $var the longest part of $Pattern that matches the front end of $var.

A usage illustration from Example A-7:

# Function from "days-between.sh" example.  # Strips
leading zero(s) from argument passed.

strip_leading_zero () #  Strip possible leading zero(s)
{                     #+ from argument passed.
  return=${1#0}       #  The "1" refers to "$1" -- passed arg.
}                     #  The "0" is what to remove from "$1" -- strips zeros.

Manfred Schwarb's more elaborate variation of the above:

strip_leading_zero2 () # Strip possible leading zero(s), since otherwise
{                      # Bash will interpret such numbers as octal values.
  shopt -s extglob     # Turn on extended globbing.
  local val=${1##+(0)} # Use local variable, longest matching series of 0's.
  shopt -u extglob     # Turn off extended globbing.
  _strip_leading_zero2=${val:-0}
                       # If input was 0, return 0 instead of "".
}

Another usage illustration:

echo `basename $PWD`        # Basename of current working directory.
echo "${PWD##*/}"           # Basename of current working directory.
echo
echo `basename $0`          # Name of script.
echo $0                     # Name of script.
echo "${0##*/}"             # Name of script.
echo
filename=test.data
echo "${filename##*.}"      # data
                            # Extension of filename.

${var%Pattern}, ${var%%Pattern}

$var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var.

$var%%Pattern} Remove from $var the longest part of $Pattern that matches the back end of $var.

Version 2 of Bash added additional options.

Example 9-18. Pattern matching in parameter substitution

#!/bin/bash
# patt-matching.sh

# Pattern matching  using the # ## % %% parameter substitution operators.

var1=abcd12345abc6789
pattern1=a*c  # * (wild card) matches everything between a - c.

echo
echo "var1 = $var1"           # abcd12345abc6789
echo "var1 = ${var1}"         # abcd12345abc6789
                              # (alternate form)
echo "Number of characters in ${var1} = ${#var1}"
echo

echo "pattern1 = $pattern1"   # a*c  (everything between 'a' and 'c')
echo "--------------"
echo '${var1#$pattern1}  =' "${var1#$pattern1}"    #         d12345abc6789
# Shortest possible match, strips out first 3 characters  abcd12345abc6789
#                                     ^^^^^               |-|
echo '${var1##$pattern1} =' "${var1##$pattern1}"   #                  6789      
# Longest possible match, strips out first 12 characters  abcd12345abc6789
#                                    ^^^^^                |----------|

echo; echo; echo

pattern2=b*9            # everything between 'b' and '9'
echo "var1 = $var1"     # Still  abcd12345abc6789
echo
echo "pattern2 = $pattern2"
echo "--------------"
echo '${var1%pattern2}  =' "${var1%$pattern2}"     #     abcd12345a
# Shortest possible match, strips out last 6 characters  abcd12345abc6789
#                                     ^^^^                         |----|
echo '${var1%%pattern2} =' "${var1%%$pattern2}"    #     a
# Longest possible match, strips out last 12 characters  abcd12345abc6789
#                                    ^^^^                 |-------------|

# Remember, # and ## work from the left end (beginning) of string,
#           % and %% work from the right end.

echo

exit 0

Example 9-19. Renaming file extensions:

#!/bin/bash
# rfe.sh: Renaming file extensions.
#
#         rfe old_extension new_extension
#
# Example:
# To rename all *.gif files in working directory to *.jpg,
#          rfe gif jpg


E_BADARGS=65

case $# in
  0|1)             # The vertical bar means "or" in this context.
  echo "Usage: `basename $0` old_file_suffix new_file_suffix"
  exit $E_BADARGS  # If 0 or 1 arg, then bail out.
  ;;
esac


for filename in *.$1
# Traverse list of files ending with 1st argument.
do
  mv $filename ${filename%$1}$2
  #  Strip off part of filename matching 1st argument,
  #+ then append 2nd argument.
done

exit 0

Variable expansion / Substring replacement

These constructs have been adopted from ksh.

${var:pos}

Variable var expanded, starting from offset pos.

${var:pos:len}

Expansion to a max of len characters of variable var, from offset pos. See Example A-14 for an example of the creative use of this operator.

${var/Pattern/Replacement}

First match of Pattern, within var replaced with Replacement.

If Replacement is omitted, then the first match of Pattern is replaced by nothing, that is, deleted.

${var//Pattern/Replacement}

Global replacement. All matches of Pattern, within var replaced with Replacement.

As above, if Replacement is omitted, then all occurrences of Pattern are replaced by nothing, that is, deleted.

Example 9-20. Using pattern matching to parse arbitrary strings

#!/bin/bash

var1=abcd-1234-defg
echo "var1 = $var1"

t=${var1#*-*}
echo "var1 (with everything, up to and including first - stripped out) = $t"
#  t=${var1#*-}  works just the same,
#+ since # matches the shortest string,
#+ and * matches everything preceding, including an empty string.
# (Thanks, Stephane Chazelas, for pointing this out.)

t=${var1##*-*}
echo "If var1 contains a \"-\", returns empty string...   var1 = $t"


t=${var1%*-*}
echo "var1 (with everything from the last - on stripped out) = $t"

echo

# -------------------------------------------
path_name=/home/bozo/ideas/thoughts.for.today
# -------------------------------------------
echo "path_name = $path_name"
t=${path_name##/*/}
echo "path_name, stripped of prefixes = $t"
# Same effect as   t=`basename $path_name` in this particular case.
#  t=${path_name%/}; t=${t##*/}   is a more general solution,
#+ but still fails sometimes.
#  If $path_name ends with a newline, then `basename $path_name` will not work,
#+ but the above expression will.
# (Thanks, S.C.)

t=${path_name%/*.*}
# Same effect as   t=`dirname $path_name`
echo "path_name, stripped of suffixes = $t"
# These will fail in some cases, such as "../", "/foo////", # "foo/", "/".
#  Removing suffixes, especially when the basename has no suffix,
#+ but the dirname does, also complicates matters.
# (Thanks, S.C.)

echo

t=${path_name:11}
echo "$path_name, with first 11 chars stripped off = $t"
t=${path_name:11:5}
echo "$path_name, with first 11 chars stripped off, length 5 = $t"

echo

t=${path_name/bozo/clown}
echo "$path_name with \"bozo\" replaced  by \"clown\" = $t"
t=${path_name/today/}
echo "$path_name with \"today\" deleted = $t"
t=${path_name//o/O}
echo "$path_name with all o's capitalized = $t"
t=${path_name//o/}
echo "$path_name with all o's deleted = $t"

exit 0
${var/#Pattern/Replacement}

If prefix of var matches Pattern, then substitute Replacement for Pattern.

${var/%Pattern/Replacement}

If suffix of var matches Pattern, then substitute Replacement for Pattern.

Example 9-21. Matching patterns at prefix or suffix of string

#!/bin/bash
# var-match.sh:
# Demo of pattern replacement at prefix / suffix of string.

v0=abc1234zip1234abc    # Original variable.
echo "v0 = $v0"         # abc1234zip1234abc
echo

# Match at prefix (beginning) of string.
v1=${v0/#abc/ABCDEF}    # abc1234zip1234abc
                        # |-|
echo "v1 = $v1"         # ABCDEF1234zip1234abc
                        # |----|

# Match at suffix (end) of string.
v2=${v0/%abc/ABCDEF}    # abc1234zip123abc
                        #              |-|
echo "v2 = $v2"         # abc1234zip1234ABCDEF
                        #               |----|

echo

#  ----------------------------------------------------
#  Must match at beginning / end of string,
#+ otherwise no replacement results.
#  ----------------------------------------------------
v3=${v0/#123/000}       # Matches, but not at beginning.
echo "v3 = $v3"         # abc1234zip1234abc
                        # NO REPLACEMENT.
v4=${v0/%123/000}       # Matches, but not at end.
echo "v4 = $v4"         # abc1234zip1234abc
                        # NO REPLACEMENT.

exit 0			
${!varprefix*}, ${!varprefix@}

Matches names of all previously declared variables beginning with varprefix.

xyz23=whatever
xyz24=

a=${!xyz*}      # Expands to *names* of declared variables beginning with "xyz".
echo "a = $a"   # a = xyz23 xyz24
a=${!xyz@}      # Same as above.
echo "a = $a"   # a = xyz23 xyz24

# Bash, version 2.04, adds this feature.

Notes

[1]

If $parameter is null in a non-interactive script, it will terminate with a 127 exit status (the Bash error code for "command not found").

'unix and linux' 카테고리의 다른 글

DNS 서버 보기  (0) 2007.10.10
crontab 이야기  (0) 2007.10.10
특정 시간마다 로그 파일 지우기.  (0) 2007.10.09
shell에서 하루 전 날짜 구하기  (0) 2007.10.09
bash에서의 String(스트링) 비교  (0) 2007.10.09
Posted by '김용환'
,

#!/bin/csh

cd /usr/local/tomcat/logs

set TARGET_LOG= (`find . -name "*.log" -print`)

@ m = 1
while ( $m <= $#TARGET_LOG )
                set LOG="$TARGET_LOG[$m]"
                /bin/cat /dev/null > ${LOG}
       @ m = $m + 1
end

'unix and linux' 카테고리의 다른 글

crontab 이야기  (0) 2007.10.10
bash shell script substitution  (0) 2007.10.09
shell에서 하루 전 날짜 구하기  (0) 2007.10.09
bash에서의 String(스트링) 비교  (0) 2007.10.09
bash에서 스트링 비교하기  (0) 2007.10.09
Posted by '김용환'
,

오늘 날짜를 구하는 것

date +%Y%m%d

 

어제 날짜를 구하는 것

date +%Y%m%d -d '-1days'

또는

date +%Y%m%d --date '1 days ago'

 

 

쉽다.

물론 man date 보고 하면 좋다.

'unix and linux' 카테고리의 다른 글

bash shell script substitution  (0) 2007.10.09
특정 시간마다 로그 파일 지우기.  (0) 2007.10.09
bash에서의 String(스트링) 비교  (0) 2007.10.09
bash에서 스트링 비교하기  (0) 2007.10.09
Bash에서 숫자 비교  (0) 2007.10.09
Posted by '김용환'
,

logical operator and 와 or은 -a, -o로 각각 표현될 수 있다.

주의할 점은 만약 &&를 사용할때는 이중 꺽쐐('[[')을 써야 한다.

 

 

출처 :http://debid.vlsm.org/share/LDP/abs/html/comparison-ops.html

 

compound comparison

-a

logical and

exp1 -a exp2 returns true if both exp1 and exp2 are true.

-o

logical or

exp1 -o exp2 returns true if either exp1 or exp2 are true.

These are similar to the Bash comparison operators && and ||, used within double brackets.

[[ condition1 && condition2 ]]
The -o and -a operators work with the test command or occur within single test brackets.
if [ "$exp1" -a "$exp2" ]

'unix and linux' 카테고리의 다른 글

특정 시간마다 로그 파일 지우기.  (0) 2007.10.09
shell에서 하루 전 날짜 구하기  (0) 2007.10.09
bash에서 스트링 비교하기  (0) 2007.10.09
Bash에서 숫자 비교  (0) 2007.10.09
Bash 간단한 내용 정리  (0) 2007.10.09
Posted by '김용환'
,

bash에서 스트링 비교할 때, 그냥 compare 기호만 쓰는 줄 알았다. 결과가 제대로 안나와서 확인도중 놀라운 사실을 발견하였다.

 

 

문자 비교시 compare 기호앞에 back slash(\)을 써야 한다는 것!!

또는 if expression 문에 '[[' 또는 ']]'을 써야 한다.

 

 

 var1=ims-google-admin

 

if [ "$var1" \> "ims" ]
then
    echo "1"
else
    echo "2"
fi

 

 

 

 

출처

http://debid.vlsm.org/share/LDP/abs/html/comparison-ops.html

 

 

string comparison

=

is equal to

if [ "$a" = "$b" ]

==

is equal to

if [ "$a" == "$b" ]

This is a synonym for =.

The == comparison operator behaves differently within a double-brackets test than within single brackets.

[[ $a == z* ]]    # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]]  # True if $a is equal to z* (literal matching).

[ $a == z* ]      # File globbing and word splitting take place.
[ "$a" == "z*" ]  # True if $a is equal to z* (literal matching).

# Thanks, Stephane Chazelas

!=

is not equal to

if [ "$a" != "$b" ]

This operator uses pattern matching within a [[ ... ]] construct.

<

is less than, in ASCII alphabetical order

if [[ "$a" < "$b" ]]

if [ "$a" \< "$b" ]

Note that the "<" needs to be escaped within a [ ] construct.

>

is greater than, in ASCII alphabetical order

if [[ "$a" > "$b" ]]

if [ "$a" \> "$b" ]

Note that the ">" needs to be escaped within a [ ] construct.

See Example 26-11 for an application of this comparison operator.

-z

string is "null", that is, has zero length

-n

string is not "null".

'unix and linux' 카테고리의 다른 글

shell에서 하루 전 날짜 구하기  (0) 2007.10.09
bash에서의 String(스트링) 비교  (0) 2007.10.09
Bash에서 숫자 비교  (0) 2007.10.09
Bash 간단한 내용 정리  (0) 2007.10.09
zagent 좀비 프로세스.  (0) 2007.10.08
Posted by '김용환'
,

 

bash에서 숫자 비교를 다음과 같이 쓸수 있다.

 

 

출처 :

http://debid.vlsm.org/share/LDP/abs/html/comparison-ops.html

 

 

-eq

is equal to

if [ "$a" -eq "$b" ]

-ne

is not equal to

if [ "$a" -ne "$b" ]

-gt

is greater than

if [ "$a" -gt "$b" ]

-ge

is greater than or equal to

if [ "$a" -ge "$b" ]

-lt

is less than

if [ "$a" -lt "$b" ]

-le

is less than or equal to

if [ "$a" -le "$b" ]

<

is less than (within double parentheses)

(("$a" < "$b"))

<=

is less than or equal to (within double parentheses)

(("$a" <= "$b"))

>

is greater than (within double parentheses)

(("$a" > "$b"))

>=

is greater than or equal to (within double parentheses)

(("$a" >= "$b"))

'unix and linux' 카테고리의 다른 글

bash에서의 String(스트링) 비교  (0) 2007.10.09
bash에서 스트링 비교하기  (0) 2007.10.09
Bash 간단한 내용 정리  (0) 2007.10.09
zagent 좀비 프로세스.  (0) 2007.10.08
포트 충돌 (zagent)  (0) 2007.10.08
Posted by '김용환'
,

 

출처 : http://invisiblepixels.org/lang/bash.html

 

History
!$ just the last word of the previous command
!! previous command (same as up arrow)
!string most recent command starting with string
!?string most recent entry containing string
^str1^str2 rerun last command replacing str1 with str2

Built-in Variables
$# no of args passed to the prog
$* reference all args passed as $1, $2, $3
$@ same as $* but references as individual string "$1" "$2" "$3"
$0 is the name of the programme
$$ process id of programme being executed
$! process id of last prog sent to background for execution
$? exit status of last command not in bg
$- current shell options in effect. see SET
IFS Internal Field Separator. What separates words (doesn't have to be a space)

Logical Comparisons
String Tests
= equals
!= not equal to
< Sorts lower
> Sorts higher
-z zero characters long
-n 1 more characters long
string string is not null
Integer Tests
-eq equals
-ne not equal to
-lt less than <
-gt greater than >
-le less than or equal to
-ge greater than or equal to
Logic
&& logical AND
|| logical OR
-a boolean and
-o boolean or
File Tests
-e exists at all
-f is ordinary file
-d is directory
-r file is readable
-w file is writable
-x file is executable
-s non empty
File Comparisons
-nt is file newer (checks modification date)
-ot is file older (checks modification date)

Loops and Decisions
if case
if decision
then
    statements
elif decision
    then
        statements
else
    statements
fi
case string
in
regexp)
    statements
;;
regexp)
    statements
;;
*)
    statements
esac
for for var in list
do
    statements
done
while while decision
do
    statements
done
until until decision
do
    statements
done

Gathering Input read
getopts

Exit Codes Success: $? = 0
Failure: $? != 0

Redirection
** 1 = STDOUT    2 = STDERR **
command 2>filename redirects STDERROR
command >&2 redirect *to* STDERROR. ie echo hello >&2 sends hello to stderror
command >foo 2>&1 redirects STDOUT to foo and STDERROR to STDOUT (which in this case is foo)
>&- causes STDOUT to go nowhere (cyberspace)
<&- causes input to come from nowhere. ie there is no input

Variable Manipulation
${var} curlies delimit var name
${var:-string} returns the string if var is empty
${var:=string} returns the string if var empty AND var is assigned the value of string
${#var} returns the length of the contents of var. or if #@ then returns no of elements in $@
${var:?string} returns string if var empty. also prints the name of var
${var:+string} returns string if variable is set. otherwise returns blank

File Permissions
perm octal notes
r 4  
w 2  
x 1  
s-- 4--- SetUid.
-s- 2--- SetGid.
--t 1--- StickyBit.
Who function What
u
g
o
a
+ (add to existing)
- (remove from existing)
= (replace existing)
r
w
x
s
t

Functions
functionname() {
local var1

statements
}
can pass parameters to it when calling it. ie functionname a b c
to terminate a function use the return n command, not exit. exit will kill the whole programme.

Arrays

Declare:

  • (Note: in that the first two examples, because you have declared the indices, you can list the elements in any random order)
    days[0]=Sunday
    days[1]=Monday
    days[2]=Tuesday
    
  • months=([01]=Jan [02]=Feb [03]=Mar)
  • With no indices declared, the elements are automatically assigned consecutive indices starting from [0].
    If you assign one of the elements an index, for example if you give autumn the index of [8]=autumn,
    all the entries following autumn will be given consecutive indices, starting from that point.
    seasons=(summer autumn winter spring)

Accessing:

  • for counter in 1 2 3 4
    do
        echo "${seasons[$counter]}"
    done
    
  • echo ${seasons[@]} or echo $seasons[*]
    The @ and * work the same way they do as $@ and $* (see top of page)

Length / Number of Elements:

  • To find out the number of non-null elements in an array: length=${#array[@]}

    If you've set up an array like this: seasons=(summer autumn [6]=winter spring),
    even though winter has an index of [6] and spring [7], ${#array[@]} will only return a value of 4.

  • To find out the length of an individual element: length=${#array[5]}

 

 

'unix and linux' 카테고리의 다른 글

bash에서 스트링 비교하기  (0) 2007.10.09
Bash에서 숫자 비교  (0) 2007.10.09
zagent 좀비 프로세스.  (0) 2007.10.08
포트 충돌 (zagent)  (0) 2007.10.08
리눅스에서 최대 파일 크기는?  (0) 2007.10.05
Posted by '김용환'
,

좀전에 zagent가 특정포트를 잡아먹었지만, 실제로는 좀비 프로세스가 된 상태이다. (바로 밑의 글 보기)

 

zagent는 자원 모니터링 프로세스이다.

이 프로세가 defunct 되면서 자원해제를 덜 되어 특정 포트를 사용할 수 없게 되었다.

 

ps -ef |grep defunct

 

를 이용하여 좀비 프로세스를 찾을 수 있다.

 

zagent가 주기적으로 좀비가 되면. 일정주기로 이용하여 다시 restart해야 한다.

 

fork방식으로 프로세스가 생성될 때, 부모프로세스에게 시그날을 송부하여 부모 프로세스가 정상적으로  자식 프로세스의 자원을 해제를 해야 하는데, 자식 프로세스가 계속 시그널을 받을 수 있는 상태가 되어 자식 프로세스는 살아있는 시체 프로세스가 된다.

 

이 수거되어 가지고 있던 자원을 해제해야 하는 자식 프로세스는 메모리와 프로세스 엔트리, 자원을 계속 hold하고 있는 상태가 되어 다른 프로세스가 해당 자원을 사용하지 못해서 피해를 볼 수 있다.

 

 

'unix and linux' 카테고리의 다른 글

Bash에서 숫자 비교  (0) 2007.10.09
Bash 간단한 내용 정리  (0) 2007.10.09
포트 충돌 (zagent)  (0) 2007.10.08
리눅스에서 최대 파일 크기는?  (0) 2007.10.05
파일시스템 타입 보기  (0) 2007.10.05
Posted by '김용환'
,

 

회사에서 아파치 + 톰캣 연결을 하는데. 여러개의 톰캣 인스턴스를 띄우기 위해서 6000번지부터 sequence하게 쭉 번호를 매기고 있다.

그런데, 특정 port에서 문제가 생겼다.

www계정으로 확인해보니. 다음과 같다.

프로세스가 안나타나서.. 당혹했지만..

 

 netstat -anp | grep 6051
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:6051                0.0.0.0:*                   LISTEN      -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33565             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33841             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33315             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33836             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33322             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33629             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33627             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33625             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33183             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33182             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33178             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33932             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33968             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33722             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33707             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33495             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33245             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33242             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33220             CLOSE_WAIT  -                  
tcp        1      0 127.0.0.1:6051              127.0.0.1:33737             CLOSE_WAIT  -                  
udp        0      0 0.0.0.0:6051                0.0.0.0:*               

 

 

root 계정으로 보니. 다행히 zagent라는 프로세스를 발견하였다.

 netstat -anp | grep 6051
tcp        0      0 0.0.0.0:6051                0.0.0.0:*                   LISTEN      6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33565             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33841             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33315             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33836             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33322             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33629             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33627             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33625             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33183             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33182             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33178             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33932             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33968             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33722             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33707             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33495             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33245             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33242             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33220             CLOSE_WAIT  6426/zagent        
tcp        1      0 127.0.0.1:6051              127.0.0.1:33737             CLOSE_WAIT  6426/zagent        
udp        0      0 0.0.0.0:6051                0.0.0.0:*                               6426/zagent    

 

아니 먼 일을 하길래, CLOSE_WAIT된 상태로 내비둔거얌.. TCP/IP 통신에서 CLOSE_WAIT는 종료하기 전에 종료 시그널을 받고 마지막 오케이만 받으면 해당 포트를 운영체제 맡겨 종료시키도록 하는 것이다.

 

그래서, zagent 환경설정파일을 보았다.

vi /etc/rc.d//init.d/zagent

#!/bin/sh

# chkconfig: 2345 99 10
# probe: true

[ -f /usr/sbin/zagent ] || exit 0

RETVAL=0

start() {
    echo -n "Starting zagent: "
    /usr/sbin/zagent -start >& /dev/null
    echo
}

stop() {
    echo -n "Shutting down zagent: "
    /usr/sbin/zagent -stop
    sleep 1
    /usr/sbin/zagent -kill
    echo
}

kill() {
    /usr/sbin/zagent -kill
}

restart() {
    stop
    sleep 1
    kill
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
                echo "Usage: zagent {start|stop|restart}"
        exit 1
esac

exit $RETVAL

 

환경설정파일은

다음과 같다.

 

 vi /var/zagent/zagent.ini

USE_WATCHDOG = 1
USERID = admin
MANAGERIP1 = 222.122.201.111
MANAGERPORT1 = 6052
MANAGERIP2 = 222.122.201.112
MANAGERPORT2 = 6052
HOSTPORT = 6051
BUFFER_MEM = off
LOCALIP =
MAX_WORK_THREADS = 5
SAVEONOFF = 0
SAVEPERIOD = 0
MANAGERTYPE = 2
HOSTNUM = 0
HOSTID = 35107

 

오호라 포트 번호가 저렇게 되어 있구나..

 

아무도 해당포트를 안쓰는지 확인하고 포트번호는 8051, 8052로 바꿨다.

데몬 재시작한다.

 

 /etc/rc.d/init.d/zagent restart

 

그리고, 문제는 사라졌다.

 

'unix and linux' 카테고리의 다른 글

Bash 간단한 내용 정리  (0) 2007.10.09
zagent 좀비 프로세스.  (0) 2007.10.08
리눅스에서 최대 파일 크기는?  (0) 2007.10.05
파일시스템 타입 보기  (0) 2007.10.05
스카시 디스크 장비 보기  (0) 2007.10.01
Posted by '김용환'
,

 

리눅스는 디폴트로 파일 크기 제한이 있다.
2G를 넘어서면 문제가 생긴다. 아파치 로그가 2G가 넘지 않아야 하고, 로그파일이 2G가 넘어가지 않도록 이메일을 통해 alert mail을 보내곤 했었다. 그래서 파일 시스템과 관련된 공부의 필요성을 느꼈다.

 

알고보니.. 꼭 그런 거만 아니더라.

 

커널 2.6은 64비트로 블럭 디바이스를 처리하는 기능이 추가되어 2TB까지의 파일시스템을 지원하게 되었다

컴파일시 다음의 옵션을 쓰면 된다고 하더라..

 
-D_LARGEFILE64_SOURCE
-D_FILE_OFFSET_BITS=64
또는
-D_GNU_SOURCE

참고자료 : /usr/include/features.h

 

ext 파일시스템 자료는 다음의 링크를 참조하시라.

http://linux390.3atec.com/cgi/cvsweb/BiBle/4.1.3.1.txt?rev=1.6


이와 관련해서 재미있는 것을 하나 찾았는데. 바로 LFS라는 것이다.
Large File Support in Linux 라는 것인데, 파일 크기때문에 스트레스를 받는다면 이걸 쓰면 될 것 같다. x86에서도 잘 돌아간다니. 쓸만할 것 같다.
대용량 파일이 필요한 곳이 생기면 써봐야겠다.

http://www.suse.de/~aj/linux_lfs.html

 

의문이 드는 게 왜 2G라는 파일 제한이 있게 된 걸까? 라는 궁금증이 있었다.

자료를 찾던 중 다음의 블로거에서 좋은 정보를 얻었다.

출처 : http://monac.egloos.com/1227726

 리눅스에서는 fopen(), open()을 통해 열 수 있는 최대 파일 크기가 2GB이다.

파일 시스템은 2G 이상의 파일을 지원할 수 있지만 표준 함수들의 제약 때문에 2GB 이상의 파일에 접근하지 못하는 문제가 생기는 것이다.

그리고, 최대 파일 크기는 표준 함수가 아니라 각 운영체제에서 제공하는 확장 함수들이 있다면, 이들 함수를 사용하기 때문에 운영체제마다 최대 파일 크기는 달라진다고 할 수 있다

 

POSIX 표준 인가에 따르면 표준 파일 함수는 최대 2GB까지로 정의되어 있다고 알고 있다 (이 부분은 내가 확인해야 겠다.)

 

 

결국은 운영체제에서 지원하는 시스템을 사용하는 프로그래밍  api의 제한때문에 제대로 활용을 못하고 있었던거 같다...

 

흐흐~~

 

'unix and linux' 카테고리의 다른 글

zagent 좀비 프로세스.  (0) 2007.10.08
포트 충돌 (zagent)  (0) 2007.10.08
파일시스템 타입 보기  (0) 2007.10.05
스카시 디스크 장비 보기  (0) 2007.10.01
csh과 bash 차이. (변환 가이드)  (0) 2007.09.12
Posted by '김용환'
,