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

Update(2019.09.08) : Add more examples to array and if statement.

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

Basic

  • 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[@]}"

Add element to array

  • Use +=
#!/bin/bash

arr_test_string=("abc" "def" "ghi" "jkl")

arr_test_string+=("mno")
arr_test_string+=("pqr" "stu")

for i in ${arr_test_string[@]}; do
	echo $i
done

arr_test_string=(1 2 3 4 5)

arr_test_string+=(6)
arr_test_string+=(7 8)

for i in ${arr_test_string[@]}; do
	echo $i
done

Delete element in array

  • Use / operator, this operator remove all characters or strings which are included in the element.
  • (Recommended) Use unset operator
#!/bin/bash

arr_test=(1 2 3)
remove_element=(3)

arr_test=( "${arr_test[@]/$remove_element}" )

for i in ${arr_test[@]}; do
	echo $i
done


arr_test=("abc" "def" "ghi")
remove_element=("ghi")

arr_test=( "${arr_test[@]/$remove_element}" )

for i in ${arr_test[@]}; do
	echo $i
done

# !!! Be careful when you delete like below !!!
# Use second method in this case

arr_test=("abc" "def" "defghi")
remove_element=("def")

arr_test=( "${arr_test[@]/$remove_element}" )

for i in ${arr_test[@]}; do
	echo $i
done
#!/bin/bash

arr_test=("abc" "def" "defghi")
remove_element=("def")

# Get index of array
echo ${!arr_test[@]}

for i in ${!arr_test[@]}; do
	if [ ${arr_test[i]} = ${remove_element} ]; then
		# Use unset
		unset arr_test[i]
	fi
done

for i in ${arr_test[@]}; do
	echo $i
done


Conditional statement

#!/bin/bash

# Numeric if statement
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 "number is not 2 or 3"
fi

# Numeric if statement
test_num=5

if (( ${test_num} > 3 )); then
	echo "number is greater than 3"
else
	echo "number is not greater than 3"
fi

# String if statement
test_str="test"

if [ "${test_str}" = "test" ]; then
	echo "test_str is test"
else
	echo "test_str is not test"
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

[Linux] 쉘 스크립트에서 멀티프로세스(혹은 스레드) 기능 사용하기

> 백그라운드로 명령어를 실행해서 병렬적으로 실행되는 멀티 프로세스 환경을 만들어보자.## 환경- Linux 기반 시스템- Bash shell(/bin/bash)## 멀티프로세스? 병렬처리? 멀티스레드? 백그라운드 프로세스?- 여기서 진행할 방식...… Continue reading