Shell Script ๊ธฐ์ด
๐ ๋ชฉ์ฐจ
0. ๊ฐ์
- shell script์ ์์์ #!๋ก ํ๋ค.
- ์ด๋ ์คํฌ๋ฆฝํธ๋ฅผ ์คํํ ์์ ์ง์ ํ๋ ์ ์ธ๋ฌธ์ด๋ค.
- ์์ bash, dash๋ก ๋๋๋ค.
- bash
#!/bin/bash
- dash์ ๋นํด ํ๋ถํ ๊ธฐ๋ฅ๊ณผ ๋ค์ํ ๋ฌธ๋ฒ์ ์ ๊ณตํ๋ค. (history ๋ฑ)
- dash
#!/bin/sh
- bash์ ๋นํด ๊ฐ๋ณ๋ค.
- ์ฌ์ฉ์์ ์ํธ์์ฉํ ์ ์๋ ๊ธฐ๋ฅ์ด ์ ๋ค.
- bash์์ ์ฌ์ฉํ๋ ์คํฌ๋ฆฝํธ๊ฐ dash์์๋ ์๋ฌ๋ฅผ ๋ฑ์ ์ ์๋ค.
- shell script ํ์ผ์ ์คํ ๊ถํ์ด ํ์ํ๋ค
chmod +x $SHELL_SCRIPT.sh
# ํ์ธ
ls -al $SHELL_SCRIPT
- ๋ณ์์ naming convention์
UPPERCASE๋ฅผ ์ฌ์ฉํ๋ค.
1. Command substitution
$(command)๋ก ์์ฑํ๋ค.
command๋ฅผ ์คํํ๊ณ , output์ ์บก์ณํ์ฌ command line์ ์ถ๊ฐํ๋ค.
2. Parameter substitution
${parameter}๋ก ์์ฑํ๋ค.
- {}๋ฅผ ""๋ก ๋์ฒด ๊ฐ๋ฅํ๋ค.
parameter๋ ๋ณ์ ์ด๋ฆ์ ๋ฃ๋๋ค.
animal=cat
echo $animal
echo ${animal}s
animal=cat
echo ${#animal}
echo ${animal/at/ow}
3. Array
arr=(obj1 obj2 obj3 ...)๋ก ์ ์ธํ๋ค.
arr[@]๋ ๋ฐฐ์ด์ ๋ชจ๋ ์์๋ฅผ ์๋ฏธํ๋ค.
- ์์ ์ถ๊ฐ๋
+=๋ก ํ๋ค.
/ ํน์ unset์ ์ด์ฉํ์ฌ ์ญ์ ํ๋ค.
unset arr[i] (๊ถ๊ณ )
arr[@]/obj1
4. Condition
if [ condition ]; then ... elif [ condition ]; then ... else fi
# example
if [ ${test} = 2 ]; then
echo "number is 2"
elif [ ${test} = 3 ]; then
echo "number is 3"
else
echo "number is not 2 or 3"
fi
5. ์ฐ์ ์ฐ์ฐ
if (( operation )); then ... else fi
# example
if (( ${test} > 3 )); then
echo "number is greater than 3"
else
echo "number is not greater than 3"
fi
6. Loop
while (()); do ... done
for idx in ${arr[@]}; do ... done
for (( i = 0; i < 10; i++ )); do ... done