[Shell Script](EN) Simple shell script syntax and usage

Simply summarize basic usage of shell script


Environment and Prerequisite

  • Linux base system
  • Bash shell(/bin/bash)


Write shell sript and allow execution permission

Make file and give permission

  • Make file
$ touch shell_script_practice.sh // 파일 생성
$ vim shell_script_practice.sh // 쉘 스크립트 파일 편집기로 열기
  • Give execution permission(change mode)
$ chmod +x shell_script_practice.sh // 실행 권한 부여


Add #!/bin/bash to top of script

#!/bin/bash

... scripts below ...


How to run shell script

  • ./[shell scipt name]
$ ./shell_script_practice.sh


Basic usage and example

Basic stdout

  • echo, printf
echo "Echo Test" # automatically add new line
printf "printf Test" # no new line
printf "%s %s" print test # print and test are arguments


  • $# : num of arguments passed to script(like argc in C)
  • $0 : name of running shell script(it includes path of shell script file when you run using path)
  • $1, $2 … : arguments passed to script(like argv[0], argv[0] in C)
#!/bin/bash

echo "Echo Test"
printf "printf Test\n"
printf "Name of script : %s\n" $0
printf "%d arguments %s %s\n" $# $1 $2


Comment

  • Use #
# echo "Echo Test"


Declare variable

  • Declare =(left is variable name and right is value) and use variable by adding $
  • {} means parameter substitution it substitutes parameter with its value(https://superuser.com/questions/935374/difference-between-and-in-shell-script)
  • Cover variable with "" so it can be more safe(we can cover space in string which is in variable). Ex) $ex -> "${ex}"
  • Use = wihtout space!
  • Add local keyword to local variable
#!/bin/bash

test="abc"
num=100

echo "${test}"
echo "${num}"


Array

  • array_name=(element1 element2 ...)
  • Array index starts with 0
  • array_name[@]means all array elements
#!/bin/bash

arr_test_string=("abc" "def" "ghi" "jkl")
echo "${arr_test_string[2]}"

arr_test_char=('a' 'b' 'b')
echo "${arr_test_char[0]}"

arr_test_num=(1 2 3 100 10000)
echo "${arr_test_num[3]}"

echo "${arr_test_num[@]}"


Conditional statement

#!/bin/bash

test_num=5

if [ "${test_num}" -eq 2 ]; then
	echo "number is 2"
elif [ "${test_num}" -eq 3 ]; then
	echo "number is 3"
else
	echo "what is it?"
fi

test_num=2

if (( "${test_num}" == 2 )); then
	echo "number is 2"
elif (( "${test_num}" == 3 )); then
	echo "number is 3"
else
	echo "what is it?"
fi


Iteration

  • while usage
#!/bin/bash

cnt=0
while (( "${cnt}" < 5 )); do
    echo "${cnt}"
    (( cnt = "${cnt}" + 1 )) # arithmetic operation needs (())
done
  • for usage
#!/bin/bash

arr_num=(1 2 3 4 5 6 7)

# @ in array index means all elements
for i in ${arr_num[@]}; do
    printf $i
done
echo

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


Reference

[Docker] 도커(Docker) 이미지 이름과 태그 목록 가져오기

> 도커(Docker) 이미지 이름과 태그 목록을 awk과 tail 명령어를 이용해 가져오는 방법을 알아보자## 환경- Linux 기반 시스템- Bash shell(/bin/bash)- Docker- awk, tail 명령어## 도커(Docker...… Continue reading