리눅스 쉘 스크립트 사용법
- Linux(Ubuntu) Shell script  (쉘스크립트) (linux shell)


//==================
* 인자 받기 (argument)
https://tecadmin.net/pass-command-line-arguments-in-shell-script/
$* = 모든 인자
$0 = 자신 이름
$1 = 첫번째 인자


//==========
* 비교
- 변수는 따옴표로 묶어야 한다.

if [ "$1" == "up" ]; then
echo up;
elif [ "$1" == "down" ]; then
echo down;
fi



//===============
* 시간
https://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/

#! /bin/bash
set -x #명령어 보이기
echo now=$(date +%y%m%d-%H%M%S)

//-----------------------------------------------------------------------------
* 현재 스크립트 파일 경로
https://stackoverflow.com/questions/59895/how-do-i-get-the-directory-where-a-bash-script-is-located-from-within-the-script

#!/usr/bin/env bash
파일 이름 = $(basename "$0")
폴더 경로 = $(dirname "$0")
실행 경로 = [$(pwd)


//-------------------------------------
* 문자열 비교
https://www.linuxtechi.com/compare-numbers-strings-files-in-bash-script/

    var1 = var2     checks if var1 is the same as string var2
    var1 != var2    checks if var1 is not the same as var2
    var1 < var2     checks if var1 is less than var2
    var1 > var2     checks if var1 is greater than var2
    -n var1             checks if var1 has a length greater than zero
    -z var1             checks if var1 has a length of zero

//-------------------------------------
* 숫자 비교
https://www.linuxtechi.com/compare-numbers-strings-files-in-bash-script/

    num1 -eq num2                  check if 1st  number is equal to 2nd number
    num1 -ge num2                  checks if 1st  number  is greater than or equal to 2nd number
    num1 -gt num2                  checks if 1st  number is greater than 2nd number
    num1 -le num2                   checks if 1st number is less than or equal to 2nd number
    num1 -lt num2                   checks if 1st  number  is less than 2nd number
    num1 -ne num2                  checks if 1st  number  is not equal to 2nd number


//-------------------------------------
* 문자열 합치기
$ X="String"
$ Y="Concatenation!"
$ echo "${X}${Y}123"

//-------------------------------------
* 명령실행 결과 값 비교
ex)
if [ $(redis-cli ping) == "PONG" ]; then       
    break
fi


//-------------------------------------
* 시간 문자열 출력
date +"%m-%d %H:%M:%S"
- 다른 문자열과 합쳐서 출력
echo  "$(date +"%m-%d %H:%M:%S") - ok"

//-----------------------------------------------------------------------------
* if 사용법
#! /bin/bash
if [ "$1" != "" ]
then
echo $1
elif [ "$2" != "" ]
then
echo $2
else
echo "none"
fi

//-------------------------------------
- (줄임) 위 코드는 다음과 같음
if [ "$1" != "" ]; then echo $1
elif [ "$2" != "" ]; then echo $2
else echo "none"
fi

//-------------------------------------
if [ "$1" != "" ]; then echo $1 
fi
- (줄임) 위 코드는 다음과 같음
[ "$1" != "" ] && echo $1

//-------------------------------------
if [ "$1" == "" ]; then echo "none"
else echo $1
fi
- (줄임) 위 코드는 다음과 같음
[ "$1" == "" ] || echo $1



//-----------------------------------------------------------------------------
* for 루프

for i in 1 2 3 4 5
do
    if [ $i -gt 2 ]; then
        break
    fi
done

//-------------------------------------
for i in {1..10}
do
    if [[ $i == '2' ]]
    then
            echo "Number $i!"
            break
    fi

        echo "$i"
i=$((i+1)) # 증가
done


//-----------------------------------------------------------------------------
* while 루프
i=1
while [ $i -le 10 ]
do
   echo $i
   if [ $i -eq 5 ]
   then
      break
   fi
   i=$((i+1)) # 증가
done

//-------------------------------------
loop=0
while true
do
    sleep 1
    loop=$((loop+1)) # 증가
    if [ $loop -gt 2 ]; then
        break
    fi
done

//-----------------------------------------------------------------------------
* function 
https://www.tutorialspoint.com/unix/unix-shell-functions.htm

# 함수 정의
Hello () {
   echo "Hello World $1 $2"
   return 10
}

# 함수 사용
Hello Zara Ali



//-------------------------------------
- .bashrc 에서 사용예

funcFind() { [ $1 != "" ] && sudo find / -name "$1"; }
alias find3='funcFind'


alias find2='cmd_arg sudo find / -name'
cmd_arg(){
        $@;
}

 

# /mnt를 제외하고 파일 검색
find2(){
        sudo find / -path "/mnt" -prune -o -name "$1" -print
}

 


//-----------------------------------------------------------------------------
* 파일에 문자열 쓰기
echo "Hello, World!" >> example.txt

//-----------------------------------------------------------------------------
실행중인 프로세스 카운트
sudo ps -aux | grep "프로세스 명령줄 이름" | wc -l

// ex)
ps_cnt=$(ps -aux | grep "artisan horizon" | wc -l)
if [ $ps_cnt -gt 1 ] ; then
        echo $(date +"%m-%d %H:%M:%S") "horizon already running $ps_cnt"
        exit
fi


//=============
//참고
http://faculty.salina.k-state.edu/tim/unix_sg/shell/variables.html#


반응형
Posted by codens