Shell Script ๊ธฐ์ดˆ

์žญ์žญ์ดยท2021๋…„ 4์›” 13์ผ

Shell Script

๋ชฉ๋ก ๋ณด๊ธฐ
1/2
post-thumbnail

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๋Š” ๋ณ€์ˆ˜ ์ด๋ฆ„์„ ๋„ฃ๋Š”๋‹ค.
# example

animal=cat
echo $animal
# cat
echo ${animal}s
# cats
# example

animal=cat
echo ${#animal}
# 3
echo ${animal/at/ow}
# cow

3. Array

  • arr=(obj1 obj2 obj3 ...)๋กœ ์„ ์–ธํ•œ๋‹ค.
  • arr[@]๋Š” ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์›์†Œ๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
  • ์›์†Œ ์ถ”๊ฐ€๋Š” +=๋กœ ํ•œ๋‹ค.
  • / ํ˜น์€ unset์„ ์ด์šฉํ•˜์—ฌ ์‚ญ์ œํ•œ๋‹ค.
    • unset arr[i] (๊ถŒ๊ณ )
    • arr[@]/obj1

4. Condition

  • usage
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. ์‚ฐ์ˆ ์—ฐ์‚ฐ

  • usage
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
while (()); do ... done
  • for
for idx in ${arr[@]}; do ... done

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

0๊ฐœ์˜ ๋Œ“๊ธ€