[컴실] shell programming

진실·2021년 10월 15일
0

변수

선언과 할당

name=sogang
name=computer 

shell에서 변수 선언은 필요하지 않다. 그냥 변수에 값을 바로 넣어주면 된다.

automatic shell varible

  • $#
    argument의 개수를 나타낸다. $1, $2, ... 등을 사용해서 첫번재 argument, 두번째 argumet에 접근할 수 있다. 다만 이와 같은 방식으로는 10을 넘어가는 argument에 대해서는 접근이 불가능하다. 즉 $10은 안된다.
  • $*
    전체 argument가 "$1 $2 ... $n" 의 형태로 저장된다.
  • $@
    전체 argument가 "$1" "$2"..."$3"과 같은 형태로 저장된다.

quoting special characters

  • \ : black slash 뒤에 있는 문자에 대해 문자 그대로 인식한다.
  • '' : single quotation mark 안에 있는 문자열에 대해 문자열 그대로 인식한다
  • "" : double quotation mark 안에 있는 문자열에 대해 변수로 인식한다.

조건문

if

if [condition]
then
	~~~~~

fi

if-else

if [condition]
then
	~
else
	~
fi

if-elif-else

if [condition]
then
	~~~
elif [condition]
	~~~~
else
	~~~~
fi

example

if [$# -eq 4]
then
	echo $4 $3 $2 $1
else
	echo Usage : $0 arg1 arg2 arg3 arg4
fi

반복문

for

syntax

for name [in list]
do
	~~~~
done

example

for dir in $PATH
do
	ls -ld $dir
done

while

syntax

while [condition]
do
	~~~~
done

example

while [ $int -lt 5 ]
do
	sq = `expr $int \* $int`
    echo $sq
    int = `expr $int +1`
done

위에 코드 분석하면서 새로 안 건데, l-value에는 $을 안붙이고 r-value에만 붙인다. 그리고 변수끼리 곱하기는 할 때는 grave accent 사이에 expr을 쓰고 그 뒤에 표현식을 쓰면 된다. `expr $int * $int` 이런식으로....

선택문

case

syntax

case expression in
    patter1)
    	statements;;
    pattern2)
    	statements;;
esac

example

echo "Is it morning? Please answer yes or no"
read timeofday
case "$timeofday" in
    yes | y | Yes | YES ) echo "Good Morning";;
    n* | N* ) echo "Good Afternoon";;
    * ) echo "Sorry, answer not recognized";;
esac
profile
반갑습니다.

0개의 댓글