2018년 2월 3일 토요일

Bash 개념 및 문법 (2)

if : 조건문, 변수와 변수끼리 또는 문자열과 비교할 때 사용함

If [ conditional expression1 ]
then
  statement1
  statement2
elif [ conditional expression2 ]
then
  statement3
  statement4
else
  statement5
fi

-eq,=,== : 같다 | -ne,!= : 같지 않다  | -gt : 초과 | -ge : 이상 | -lt : 미만 | -le : 이하 | -z : 문자열이 NULL임 | -n : 문자열이 NULL이 아님

for : 반복문, 변수 안에 있는 값을 반복하거나 범위를 지정하여 반복할 수 있음

for i in $(ls)
do
  echo $i
done

for (( i=0; i < 10; i++ ))
do
  echo $i
done

NUM=( 1 2 3 )
for i in ${NUM[0]}
do
  echo $i
done

while : while 반복문

while :
do
  echo "Hello World";
  sleep 1;
done

<<< : 문자열을 명령(프로세스)의 표준 입력으로 보냄
$ cat <<< "User name is $USER"

<<EOF ~ EOF : 여러 줄의 문자열을 명령(프로세스)의 표준 입력으로 보냄

# cat 의 표준 출력을 hello.txt로 저장, <<EOF로 문자열을 cat의 표준 입력으로 보냄
$ cat > ./hello.txt << EOF
Hello World
Host name is $(hostname)
User name is $USER
EOF

export : 설정한 값을 환경 변수로 만듬 (export <변수>=<값>)
$ export HELLO=world

printf : 지정한 형식대로 값을 출력함, 파이프와 연동하여 명령(프로세스)에 값을 입력하는 효과를 나타낼 수 있음

$ printf 80\\nexampleuser\\ny | example-confg
Port : 80
User : exampleuser
Save Configuration (y/n) : y

printf로 미리 값을 설정하여 파이프로 example-config에 넘겨주면 사용자가 입력하지 자동 입력, \\n은 개행문자임

sed : 텍스트 파일에서 문자열을 변경함.
sed -i "s/<찾을 문자열>/<바꿀문자열>/g" <파일명>

$ sed -i "/shello/world/g" hello.txt

# : 주석 처리