csh 스크립트를 정리하다가. 발견한 사실.. (이미 오래전에 적었을지도 모르지만.. ^^;;)

 

#!/bin/csh

 wget -O serverStatusLog 'http://127.0.0.1/server-status?auto';
cat serverStatusLog | awk -F: '{ print $2 }' > statusCurrent

set current=(`cat statusCurrent`)

 

csh에서의 ( ) 마크는 bash 에서는 다르게 해석한다고 말했는데..  

csh에서는 개행문자뿐 아니라 사이띄기도 ( )를 이용하면 배열로 만들 수 있는데 반해서

bash에서는 오직 개행문자만 배열로 만들 수 있다.

 

만약 개행문자로 나눌 수 있는 값이면, 아래처럼 그래도 쓸 수 있다.

 

#!/bin/csh

 wget -O serverStatusLog 'http://127.0.0.1/server-status?auto';
cat serverStatusLog | awk -F: '{ print $2 }' > nstatusCurrent

current=(`cat nstatusCurrent`)

 

그러나, 스페이로 이루어질 때는 tr을 이용해서 배열로 만들면 된다.

 

#!/bin/csh

 wget -O serverStatusLog 'http://127.0.0.1/server-status?auto';
cat serverStatusLog | awk -F: '{ print $2 }' > nstatusCurrent

current=`echo nstatusCurrent | tr ' ' ' '`

 

 

Posted by '김용환'
,

 #!/bin/bash

# Linux Version
cat /proc/version

# Redhat Version
redhatVersion=`cat /etc/redhat-release`
echo $redhatVersion

# Memory Total Size
cat /proc/meminfo | grep MemTotal | awk '{print $2$3}'

# CPU model
cat /proc/cpuinfo | grep 'model name' | head -n 1

# CPU Number
cat /proc/cpuinfo | grep processor | wc -l

# Disk Information
df=`df -h |  grep -v grep `
echo -n "$df"

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

How to get the biggest filesystem In all filesystem  (0) 2009.06.09
bash와 csh의 차이점  (0) 2009.03.24
시스템 정보 가지고 오기 #1  (0) 2009.03.24
bash 에서 ( 사용관련 팁  (0) 2009.03.24
SED 튜터리얼 sed tutorial  (0) 2009.03.13
Posted by '김용환'
,

 #!/bin/bash

# Configuration
DEBUG_FALSE=0
DEBUG_TRUE=1
DEBUG_TYPE=$DEBUG_FALSE
SLEEP_TIME=1
ETH_TYPE=eth0
SLEEP_TIME=1

KB=128

if [ $DEBUG_TYPE == "1" ]; then
    echo " D) debug mode "
fi

# Network Inbound / Outbound

before=`cat /proc/net/dev | grep $ETH_TYPE | cut -f2 -d: | awk '{print $1, $9}'`
nbefore=(`echo $before | tr '.' ' '`)
sleep $SLEEP_TIME
after=`cat /proc/net/dev | grep $ETH_TYPE | cut -f2 -d: | awk '{print $1, $9}'`
nafter=(`echo $after | tr '.' ' '`)

inboundtemp=`expr ${nafter[0]} - ${nbefore[0]}`
inbound=`expr $inboundtemp / $KB / $SLEEP_TIME`
outboundtemp=`expr ${nafter[1]} - ${nbefore[1]}`
outbound=`expr $outboundtemp / $KB / $SLEEP_TIME`

if [ $DEBUG_TYPE == $DEBUG_TRUE ]; then
        echo " D) sleep time : $SLEEP_TIME"
        echo " D) inbound temp : $inboundtemp"
        echo " D) outbound temp : $outboundtemp"
fi

echo $inbound,$outbound

# CPU value
#cat /proc/stat | grep -e '^cpu ' | grep -v grep | awk '{print $0}' > cpudata
ncpuinfo=`cat /proc/stat | grep -e '^cpu ' | grep -v grep | awk '{print $0}'`
cpuinfo=(`echo $ncpuinfo | tr '.' ' '`)
if [ $DEBUG_TYPE == $DEBUG_TRUE ]; then
        echo " D) cputime : ${cpuinfo[1]}, ${cpuinfo[2]}, ${cpuinfo[3]}, ${cpuinfo[4]}, ${cpuinfo[5]}"
fi

beforeCpuinfo1=${cpuinfo[1]}
beforeCpuinfo2=${cpuinfo[2]}
beforeCpuinfo3=${cpuinfo[3]}
beforeCpuinfo4=${cpuinfo[4]}
beforeCpuinfo5=${cpuinfo[5]}

sleep $SLEEP_TIME

ncpuinfo=`cat /proc/stat | grep -e '^cpu ' | grep -v grep | awk '{print $0}'`
cpuinfo=(`echo $ncpuinfo | tr '.' ' '`)

user=`expr ${cpuinfo[1]} - $beforeCpuinfo1`
system=`expr ${cpuinfo[2]} - $beforeCpuinfo2`
nice=`expr ${cpuinfo[3]} - $beforeCpuinfo3`
idle=`expr ${cpuinfo[4]} - $beforeCpuinfo4`
iowait=`expr ${cpuinfo[5]} - $beforeCpuinfo5 `
total=`expr $user + $system + $nice + $idle + $iowait`

echo $total, $idle

# Load Average
#cat /proc/loadavg  | awk '{print $1}'
nloadavg=`cat /proc/loadavg  | awk '{print $1,$2,$3}'`
loadavg=(`echo $nloadavg | tr ' ' ' '`)
echo ${loadavg[0]}, ${loadavg[1]}, ${loadavg[2]}

# IO read / write
home=`df . | grep '/' | awk '{print $1}' | cut -d'/' -f3-`
niostats=`iostat $home -d 1 1 | grep $home | awk '{print $3, $4}'`
iostats=(`echo $niostats | tr '.' ' '`)
echo ${iostats[0]}, ${iostats[1]}

# Free / Swap memory
totalMemory=`cat /proc/meminfo | grep MemFree | awk '{print $2$3}'`
swapMemory=`cat /proc/meminfo | grep SwapFree | awk '{print $2$3}'`
echo $totalMemory, $swapMemory

 

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

bash와 csh의 차이점  (0) 2009.03.24
시스템 정보 받아오기 #2  (0) 2009.03.24
bash 에서 ( 사용관련 팁  (0) 2009.03.24
SED 튜터리얼 sed tutorial  (0) 2009.03.13
쉘 에러 bad interpreter:  (0) 2008.12.12
Posted by '김용환'
,

 

shell에서 다음을 실행시켰더니 원하는 숫자 정보가 나왔다.

shell> cat /proc/net/dev | grep eth0 | cut -f2 -d: | awk '{print $1, $9}'
3495437713 2251687131

bash 프로그래밍에서 다음의 차이점은 무엇일까?

 

 after=(`cat /proc/net/dev | grep eth0 | cut -f2 -d: | awk '{print $1, $9}'`)
echo ${after}

 

 

 after=`cat /proc/net/dev | grep eth0 | cut -f2 -d: | awk '{print $1, $9}'`
echo ${after}

 

( ) 를 추가하고 안한 차이인데.. 우선 결과값을 보자

 

 

 after=(`cat /proc/net/dev | grep eth0 | cut -f2 -d: | awk '{print $1, $9}'`)
echo ${after}

 => 3495580030

 

 after=`cat /proc/net/dev | grep eth0 | cut -f2 -d: | awk '{print $1, $9}'`
echo ${after}

=> 3496364409 2252368302

 

즉 shell에서 명령어를 통해서 받아낸 결과값을 변수에 해당 값을 할당할 때, ( ) 를 추가하면, 스페이스나 개행문자에 관련해서 스스로 파싱하여 첫번째 값만 가지게 된다..

 

 

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

시스템 정보 받아오기 #2  (0) 2009.03.24
시스템 정보 가지고 오기 #1  (0) 2009.03.24
SED 튜터리얼 sed tutorial  (0) 2009.03.13
쉘 에러 bad interpreter:  (0) 2008.12.12
/etc/sudoers  (0) 2008.11.19
Posted by '김용환'
,

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

시스템 정보 가지고 오기 #1  (0) 2009.03.24
bash 에서 ( 사용관련 팁  (0) 2009.03.24
쉘 에러 bad interpreter:  (0) 2008.12.12
/etc/sudoers  (0) 2008.11.19
ipcs  (0) 2008.11.07
Posted by '김용환'
,

: bad interpreter:  No such file or directory

 

파일이 바이너리인지, 아니면,  \r\n CR/LF 문제인지 확인하면 오케

 

 

 

 

 

 

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

bash 에서 ( 사용관련 팁  (0) 2009.03.24
SED 튜터리얼 sed tutorial  (0) 2009.03.13
/etc/sudoers  (0) 2008.11.19
ipcs  (0) 2008.11.07
파일 길이가 큰 파일 옮기기 (split를 이용하여 리눅스 파일 나누기 합치기)  (0) 2008.06.26
Posted by '김용환'
,

/etc/sudoers

unix and linux 2008. 11. 19. 22:53

iptables 명령어를 www계정으로 들어오는 사용자에게 쓸 수 있게 하기

 

 

chattr -i /etc/sudoers
chmod u+w /etc/sudoers

echo "Defaults:www \!authenticate" >> /etc/sudoers
echo "Cmnd_Alias CMD=/sbin/ifup,/sbin/ifdown,/sbin/iptables" >> /etc/sudoers
echo "www ALL=CMD:ALL=/sbin/swapon" >> /etc/sudoers

chmod u-w /etc/sudoers
chattr +i /etc/sudoers

Posted by '김용환'
,

ipcs

unix and linux 2008. 11. 7. 20:40

IPC(Inter Process Communication)는 message queue( q), shared mem ( m), semaphore (s)의 자원의 현황을 알려준다.

 

ipcs -l 을 사용하였다.

 


------ Shared Memory Limits --------
max number of segments = 4096
max seg size (kbytes) = 1048576
max total shared memory (kbytes) = 8388608
min seg size (bytes) = 1

------ Semaphore Limits --------
max number of arrays = 128
max semaphores per array = 250
max semaphores system wide = 32000
max ops per semop call = 32
semaphore max value = 32767

------ Messages: Limits --------
max queues system wide = 16
max size of message (bytes) = 8192
default max size of queue (bytes) = 16384

 

 

ipcs 만 치면 이렇게 나온다.

 

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status     

------ Semaphore Arrays --------
key        semid      owner      perms      nsems    
0x00000000 3964928    www       600        1        
0x00000000 3997697    www       600        1        
0x00000000 4030466    www       600        1        
0x00000000 4063235    www       600        1        
0x00000000 4096004    www       600        1        

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages   

 

자원을 삭제할 때는 ipcrm 라는 명령어를 사용하면 된다.

 

왜 이런 것이 필요할까?

 

그것은 특정 프로세스가 가지고 있던 자원들을 해제하지 않으면서 생긴 문제를 해결하기 위함이다.

예를 들어 DBMS에 대해서 kill을 했지만, IPC 자원을 해제않는 경우를 확인할 수 있고, 이를 통해서 자원이 낭비되고, 이런식으로 계속 문제가 되면, 시스템 전체에 영향을 미칠 수 있기 때문이다.

 

예를 들어 apache 데몬의 경우 restart를 했는데, 다음과 같이 세마포를 계속 가지고 있을 수 있다.

 

------ Semaphore Arrays --------
key        semid      owner      perms      nsems    
0x00000000 13434880   www       600        1        
0x00000000 13467649   www       600        1        
0x00000000 13500418   www       600        1        
0x00000000 13533187   www       600        1        
0x00000000 13565956   www       600        1 

....

....

....

 

 

 

그러면,

ipcs -s |sed "/em/d" | for i in `awk '{print $2}'` ; do ipcrm sem $i ; done

 

이 명령어를 통해서 싹 정리하면 좋다.

 

 

Posted by '김용환'
,

 

옮길 디렉토리를 압축하니 3G가 나왔다.

ftp, rcp, scp 로 하려니 너무 크다는 메시지..

 

결국 500메가 단위로 잘라냈는데..

 

 split -b 500m data_home.tar.gz

 

이렇게 하면,

xaa

xab

xac

...

 

이렇게  잘라진다.

 

ftp로 복사 잘된다

 

붙일때는 다음의 명령어를 사용하면 된다.

 

cat x* > data_home.tar.gz

 

 

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

/etc/sudoers  (0) 2008.11.19
ipcs  (0) 2008.11.07
bash 문자열 조작  (0) 2008.06.20
고급 Bash 스크립팅 가이드  (0) 2008.06.20
특정 디렉토리에서 파일명 뽑아내기  (0) 2008.06.20
Posted by '김용환'
,

 

bash shell에서 문자열 조작할 때 편하게 쓸 수 있도록 KLDP가 이렇게 작업하였다니~

정말 감사하다!!!!

 

 

http://kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/string-manipulation.html

 

 

9.2. 문자열 조작

Bash 는 놀랍도록 많은 문자열 조작 연산을 제공합니다. 하지만 불행하게도 이 도구들은 하나로 통합되어 있지 않습니다. 몇 개는 매개변수 치환의 서브셋이고 다른 것은 유닉스의 expr 명령어의 기능에 해당합니다. 이렇기 때문에 이런 혼동스러움에 대한 언급도 없이 명령어 문법에 일관성이 없고 기능이 중복되어 있습니다.

문자열 길이

${#string}

expr length $string

expr "$string" : '.*'

stringZ=abcABC123ABCabc

echo ${#stringZ}                 # 15
echo `expr length $stringZ`      # 15
echo `expr "$stringZ" : '.*'`    # 15

문자열 시작에서부터 매칭되는 문자열조각(substring)의 길이

expr match "$string" '$substring'

$substring정규 표현식입니다.

expr "$string" : '$substring'

$substring 은 정규 표현식입니다.

stringZ=abcABC123ABCabc
#       |------|

echo `expr match "$stringZ" 'abc[A-Z]*.2'`   # 8
echo `expr "$stringZ" : 'abc[A-Z]*.2'`       # 8

인덱스

expr index $string $substring

$string 에서 일치하는 $substring 의 첫 문자의 위치.

stringZ=abcABC123ABCabc
echo `expr index "$stringZ" C12`             # 6
                                             # C 의 위치.

echo `expr index "$stringZ" 1c`              # 3
# 'c' (3번째 위치에 있는) 가 '1' 보다 먼저 일치됨.

C 의 strchr()와 거의 비슷합니다.

문자열조각 추출(Substring Extraction)

${string:position}

$string$position 부터의 문자열조각을 추출.

string 매개변수가 "*" 이거나 "@" 라면 position에서 시작하는 위치 매개변수 [1] 를 추출해 냅니다.

${string:position:length}

$string$position부터 $length만큼의 문자를 추출해 냅니다.

stringZ=abcABC123ABCabc
#       0123456789.....
#       0 부터 시작하는 인덱싱.

echo ${stringZ:0}                            # abcABC123ABCabc
echo ${stringZ:1}                            # bcABC123ABCabc
echo ${stringZ:7}                            # 23ABCabc

echo ${stringZ:7:3}                          # 23A
                                             # 3글자짜리 문자열조각.

string 매개변수가 "*""@" 라면 위치 position에서 시작하는 매개변수의 최대 length를 추출해 냅니다.

echo ${*:2}          # 두번째 이후의 위치 매개변수를 에코.
echo ${@:2}          # 위와 같음.

echo ${*:2:3}        # 2,3,4번(3개) 위치 매개변수를 에코.

expr substr $string $position $length

$string$position부터 $length만큼의 문자를 추출해 냅니다.

stringZ=abcABC123ABCabc
#       123456789......
#       1 부터 시작하는 인덱싱.

echo `expr substr $stringZ 1 2`              # ab
echo `expr substr $stringZ 4 3`              # ABC

expr match "$string" '\($substring\)'

$string의 처음에서부터 정규 표현식$substring을 추출해 냅니다.

expr "$string" : '\($substring\)'

$string의 처음에서부터 정규 표현식인 $substring을 추출해 냅니다.

stringZ=abcABC123ABCabc

echo `expr match "$stringZ" '\(.[b-c]*[A-Z]..[0-9]\)'`   # abcABC1
echo `expr "$stringZ" : '\(.[b-c]*[A-Z]..[0-9]\)'`       # abcABC1
# 위의 두 가지 형태는 동일합니다.

문자열조각 삭제(Substring Removal)

${string#substring}

$string앞 부분에서부터 가장 짧게 일치하는 $substring을 삭제.

${string##substring}

$string앞 부분에서부터 가장 길게 일치하는 $substring을 삭제.

stringZ=abcABC123ABCabc
#       |----|
#       |----------|

echo ${stringZ#a*C}      # 123ABCabc
# 'a'와 'C' 사이에서 가장 짧게 일치되는 부분을 삭제.

echo ${stringZ##a*C}     # abc
# 'a'와 'C' 사이에서 가장 길게 일치되는 부분을 삭제.

${string%substring}

$string뒷 부분에서부터 가장 짧게 일치하는 $substring을 삭제.

${string%%substring}

$string뒷 부분에서부터 가장 길게 일치하는 $substring을 삭제.

stringZ=abcABC123ABCabc
#                    ||
#        |------------|

echo ${stringZ%b*c}      # abcABC123ABCa
# $stringZ의 뒷 부분부터 계산해서 'b'와 'c' 사이에서 가장 짧게 일치하는 부분을 삭제.

echo ${stringZ%%b*c}     # a
# $stringZ의 뒷 부분부터 계산해서 'b'와 'c' 사이에서 가장 길게 일치하는 부분을 삭제.

예 9-9. 그래픽 파일을 다른 포맷 확장자로 이름을 바꾸면서 변환

#!/bin/bash
#  cvt.sh:
#  특정 디렉토리의 모든 MacPaint 이미지 파일을 "pbm" 포맷으로 변환.

#  Brian Henderson(bryanh@giraffe-data.com)이 관리하고 있는 "netpbm" 패키지의
#+ "macptopbm" 을 사용함.
#  Netpbm 은 거의 대부분의 리눅스 배포판에 포함되어 있습니다.

OPERATION=macptopbm
SUFFIX=pbm          # 새 파일이름 확장자. 

if [ -n "$1" ]
then
  directory=$1      # 디렉토리 이름이 인자로 주어질 경우...
else
  directory=$PWD    # 아니면 현재 디렉토리에 대해서.
fi  
  
# 대상 디렉토리의 모든 파일을 ".mac" 확장자의 MacPaint 이미지 파일이라고 가정.

for file in $directory/*    # 파일이름 globbing.
do
  filename=${file%.*c}      #  파일이름에서 ".mac" 확장자를 떼어냄
                            #+ ('.*c' 는 '.' 과 'c'를 포함해서 둘 사이의 
                            #+ 모든 것과 일치함).
  $OPERATION $file > $filename.$SUFFIX
                            # 변환된 파일을 새 파일이름으로 재지향.
  rm -f $file               # 변환후 원래 파일 삭제.
  echo "$filename.$SUFFIX"  # 결과를 표준출력으로 로깅.
done

exit 0

문자열 조각 대치(Substring Replacement)

${string/substring/replacement}

처음 일치하는 $substring$replacement로 대치.

${string//substring/replacement}

일치하는 모든 $substring$replacement로 대치.

stringZ=abcABC123ABCabc

echo ${stringZ/abc/xyz}           # xyzABC123ABCabc
                                  # 처음 일치하는 'abc'를 'xyz'로 대치.

echo ${stringZ//abc/xyz}          # xyzABC123ABCxyz
                                  # 일치하는 모든 'abc'를 'xyz'로 대치.

${string/#substring/replacement}

$substring$string맨 앞에서 일치하면 $replacement로 대치.

${string/%substring/replacement}

$substring$string맨 뒤에서 일치하면 $replacement로 대치.

stringZ=abcABC123ABCabc

echo ${stringZ/#abc/XYZ}          # XYZABC123ABCabc
                                  # 맨 앞에서 일치하는 'abc'를 'xyz'로 대치.

echo ${stringZ/%abc/XYZ}          # abcABC123ABCXYZ
                                  # 맨 뒤에서 일치하는 'abc'를 'xyz'로 대치.

스크립트에서 문자열 조작에 대한 더 자세한 사항은 9.3절expr 명령어에서 문자열 조작과 관련된 부분을 참고하세요. 스크립트 예제는 다음을 참고하세요.

  1. 예 12-6

  2. 예 9-11

  3. 예 9-12

  4. 예 9-13

  5. 예 9-15

주석

[1]

이 규칙은 명령어줄 인자나 함수로 넘겨지는 매개변수에도 적용됩니다.

 

 

Posted by '김용환'
,