티스토리 뷰

개발 노트/Linux

linux bash 응용

오리지날초이 2013. 12. 3. 15:08

[인자 표현]

인자의 표현은 $tmp 가 아니라 ${tmp} 가 좋다

인자명에서 _, 숫자 등을 연결해 써야할 때, 가독성에서 유리 

인자명을 $(var) 와 응용해서 사용하는데도 편리하다

[localhost:/tmp] cat 1.sh

#!/bin/bash


tmpfile="/tmp/tmp1"

echo ${tmpfile}

echo "=================="


msg=${tmpfile}

echo ${msg}

echo "=================="


msg=$(< ${tmpfile})

echo ${msg}

echo "=================="


msg=$(cat ${tmpfile})

echo ${msg}

echo "=================="


msg=$(${tmpfile})

echo ${msg}

echo "=================="


msg=$(sh ${tmpfile})

echo ${msg}


[localhost:/tmp] cat tmp1

tmp1

tmp2

tmp3

tmp4


[localhost:/tmp] sh 1.sh

/tmp/tmp1

==================

/tmp/tmp1

==================

tmp1 tmp2 tmp3 tmp4

==================

tmp1 tmp2 tmp3 tmp4

==================

1.sh: line 19: /tmp/tmp1: 허가 거부됨


==================

/tmp/tmp1: line 1: tmp1: command not found

/tmp/tmp1: line 2: tmp2: command not found

/tmp/tmp1: line 3: tmp3: command not found

/tmp/tmp1: line 4: tmp4: command not found


[위치 파라미터]

set : 위치 파라미터에 값을 할당함

set -- : 앞서 설정된 파라미터 값 제거

eval : 실행전의 명령라인 파싱

$# : 파라미터 갯수

$* : 파라미터 모든 값

[localhost:/root] echo $#

4

[localhost:/root]

[localhost:/root] echo $*

linux fedora centos excellent

[localhost:/root] echo $#

4

[localhost:/root] echo \$$#

$4

[localhost:/root] eval echo \$$#

excellent

[localhost:/root] set --

[localhost:/root] echo $*


[localhost:/root]


[기타 특수 변수]

$ : 쉘의 프로세스 ID

- : 배쉬 쉘의 모든 옵션 목록

? : 마지막 실행한 명령의 종료상태 값

! : 백그라운드 실행되고 있는 마지막 명령의 PID 값

[localhost:/root] echo $$

30079

[localhost:/root] echo $?

0

[localhost:/root] echo $!


[localhost:/root] echo $-

himBH

[localhost:/root] ps -ef | grep 30079

root       927 30079  0 15:07 pts/0    00:00:00 ps -ef

root       928 30079  0 15:07 pts/0    00:00:00 grep 30079

root     30079 29709  0 14:59 pts/0    00:00:00 -bash


[trap & signal]

trap 설명

signal 설명

#!/bin/sh

errfile=${TMP_DIR}/$$

trap "rm -f ${errfile}" EXIT SIGINT SIGTERM


[let]

#!/bin/sh

let sleep_time=$5*60


[timeout]

NAME

       timeout - run a command with a time limit


SYNOPSIS

       timeout [OPTION] NUMBER[SUFFIX] COMMAND [ARG]...

       timeout [OPTION]


DESCRIPTION

       Start COMMAND, and kill it if still running after NUMBER seconds.  SUFFIX may be ‘s’ for seconds (the default), ‘m’ for minutes, ‘h’ for hours or ‘d’ for days.


       Mandatory arguments to long options are mandatory for short options too.


       -s, --signal=SIGNAL


              specify the signal to be sent on timeout.  SIGNAL may be a name like ‘HUP’ or a number.  See ‘kill -l‘ for a list of signals


       --help display this help and exit


       --version

              output version information and exit


       If  the command times out, then exit with status 124.  Otherwise, exit with the status of COMMAND.  If no signal is specified, send the TERM signal upon timeout.  The TERM signal kills any process that does

       not block or catch that signal.  For other processes, it may be necessary to use the KILL (9) signal, since this signal cannot be caught.


#bin/sh

timeout ${timeout} sh ${shell_script} ${cid} ${yyyymmdd} 2> ${errfile}


[test]


                                                 TEST(1L)


이름

       test - 화일 유형을 점검하고 값을 비교한다.


개요

       test [표현식]

       test {--help,--version}


설명

       이 맨페이지는 GNU 버전의 test 를 다룬다.  대부분의 쉘은 같은 이름, 같은 기능의 내장 명령을 지니고 있을 것이다.


       test 조건 표현식의 평가에 따라 0 (참) 또는 1 (거짓)의 상태를 반환한다.  expr.  은 단항식(unary) 또는 이항식(binary)가 될 수 있다. 단항식은보통 화일의 상태를 조사하

       는데 사용된다.  문자열 연산잔와 수치 비교 연산자도 있다.


       -b 화일

              만약 화일 이 존재하며 블럭 장치이며 참.

       -c 화일

              만약 화일 이 존재하고 문자 장치이면 참.

       -d 화일

              만약 화일 이 존재하고 디렉토리이면 참.

       -e 화일

              만약 화일 이 존재하면 참.

       -f 화일

              만약 화일 이 존재하고 보통의 화일이면 참.

       -g 화일

              만약 화일 이 존재하고 set-group-id 이면 참.

       -k 화일

              만약 화일 이 ‘‘sticky’’ 비트 설정을 가지고 있으면 참.

       -L 화일

              만약 화일 이 존재하고 심복릭 링크이면 참.

       -p 화일

              만약 화일 이 존재하고 명명된 파이프이면 참.

       -r 화일

              만약 화일 이 존재하고 읽기 가능이면 참.

       -s 화일

              만약 화일 이 존재하고 0 보다 큰 크기를 갖으면 참.

       -S 화일

              만약 화일 이 존재하고 소켓이면 참.

       -t [fd]

              만약 fd 가 터미널 상에서 오픈된 것이면 참.  만약 fd 가 생략되면 기본값은 1 ( 표준출력 )이다.

       -u 화일

              만약 화일 이 존재하고 set-user-id 비트 설정을 가지면 참.

       -w 화일

              만약 화일 이 존재하고 쓰기가능이면 참.

       -x 화일

              만약 화일 이 존재하고 실행가능이면 참.

       -O 화일

              만약 화일 이 존재하고 유효 사용자 ID의 소유이면 참.

       -G 화일

              만약 화일 이 존재하고 유효 그룹 ID의 소유이면 참.

       화일1 -nt 화일2

              만약 화일1 이 (수정일에 의거하여) 화일2보다 최근에 생겼다면 참.

       화일1 -ot 화일2

              만약 화일1 이 화일2보다 오래된 것이면 참.

       화일1 -ef 화일2

              만약 화일1 과 화일2 이 같은 장치, 같은 아이노드 번호를 갖는다면참.

       -z 문자열

              만약 문자열의 길이가 0 이면 참.

       -n 문자열

       string 문자열의 길이가 0 이 아니라면 참.

       문자열1 = 문자열2

              두 문자열이 같으면 참.

       문자열1 != 문자열2

              두 문자열이 같지 않으면 참.

       ! 표현식

              표현식이 거짓이면 참.

       표현식1 -a 표현식2

              표현식1 과 표현식2 가 둘 다 참이면 참.

       표현식1 -o 표현식2

              표현식1 또는 표현식2 둘 중 하나라도 참이면 참.

       인수1 OP 인수2

              여기서 OP 는 다음 중 하나이다.  -eq, -ne, -lt, -le, -gt, 또는 -ge.  

  이러한 수치 이항 연산자들은 각각 만약 인수1이 인수2보다 같거나, 같지 않거나, 작거나,  작거나 같거나, 크거나, 크거나 같을 때 참을   반환한다.  인수1 와 arg2 는 양의 정수, 음의 정수 또는 문자열의 길이를 평가하는 -l 문자열 표현식이 될 수 있다.

   옵션

       GNU test 가 단 한 개의 인수로 시작하면 다음 옵션이 인식된다:

       --help 표준출력으로 사용법을 출력하고 정상적으로 종료한다.

       --version

              표준출력으로 버전정보를 출력하고 정상적으로 종료한다.

번역자

       이 만 용 <geoman@nownuri.nowcom.co.kr>

                <freeyong@soback.kornet.nm.kr>


#!/bin/sh
exist()
{
test -f "/direcotry/""$1"

return $?

}


[stat]


Usage: stat [OPTION] FILE...

Display file or file system status.


  -L, --dereference     follow links

  -Z, --context         print the security context information if available

  -f, --file-system     display file system status instead of file status

  -c  --format=FORMAT   use the specified FORMAT instead of the default;

                          output a newline after each use of FORMAT

      --printf=FORMAT   like --format, but interpret backslash escapes,

                          and do not output a mandatory trailing newline.

                          If you want a newline, include \n in FORMAT.

  -t, --terse           print the information in terse form

      --help     이 도움말을 표시하고 끝냅니다

      --version  버전 정보를 출력하고 끝냅니다


The valid format sequences for files (without --file-system):


  %a   Access rights in octal

  %A   Access rights in human readable form

  %b   Number of blocks allocated (see %B)

  %B   The size in bytes of each block reported by %b

  %d   Device number in decimal

  %D   Device number in hex

  %f   Raw mode in hex

  %F   File type

  %g   Group ID of owner

  %G   Group name of owner

  %h   Number of hard links

  %i   Inode number

  %n   File name

  %N   Quoted file name with dereference if symbolic link

  %o   I/O block size

  %s   Total size, in bytes

  %t   Major device type in hex

  %T   Minor device type in hex

  %u   User ID of owner

  %U   User name of owner

  %x   Time of last access

  %X   Time of last access as seconds since Epoch

  %y   Time of last modification

  %Y   Time of last modification as seconds since Epoch

  %z   Time of last change

  %Z   Time of last change as seconds since Epoch


Valid format sequences for file systems:


  %a   Free blocks available to non-superuser

  %b   Total data blocks in file system

  %c   Total file nodes in file system

  %d   Free file nodes in file system

  %f   Free blocks in file system

  %C   Security context in SELinux

  %i   File System ID in hex

  %l   Maximum length of filenames

  %n   File name

  %s   Block size (for faster transfers)

  %S   Fundamental block size (for block counts)

  %t   Type in hex

  %T   Type in human readable form


NOTE: your shell may have its own version of stat, which usually supersedes

the version described here.  Please refer to your shell's documentation

for details about the options it supports.


#!/bin/sh

local_file_size=$(stat --print %s ${local_file})


[날짜 역순 처리]

TOP_DATE="20121220"

BOTTOM_DATE="20110601"


while true

do

        if [ $TOP_DATE -lt $BOTTOM_DATE ]; then

                break

        else

                echo $TOP_DATE

                ${WORK_DIR}/work.sh ${TOP_DATE}

                TOP_DATE=$(date --date "${TOP_DATE} 1 day ago" '+%Y%m%d')

        fi

done


728x90
반응형

'개발 노트 > Linux' 카테고리의 다른 글

원격파일 복사  (0) 2014.04.22
리눅스 bash 고급  (0) 2014.02.24
System monitoring tool in linux  (0) 2013.11.27
find 명령어 활용  (0) 2013.11.01
tcp port open 확인  (0) 2013.11.01
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함