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

Update(2020.12.26): Add contents of parameter expansion and quote about variable

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 // create file
$ vim shell_script_practice.sh // open file with editor
  • Give execution permission(change mode)
$ chmod +x shell_script_practice.sh // add execution permission


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 $
  • Use = wihtout space!
  • Add local keyword to local variable
  • {} is parameter expansion it substitutes parameter with its value(https://superuser.com/questions/935374/difference-between-and-in-shell-script) It can be used in various ways through various expression methods.
  • It can set default value like default_value=${default_value:="example default value"} when variable value is not set or not declared.
  • Cover variable with "" so it can be more safe because we can cover space in string which is in variable. Ex) $ex -> "${ex}"
#!/bin/bash

# shell script variable
test="abc"
num=100

# variable usage
echo ${test}
echo ${num}
echo "${test}"
echo "${num}"

# local variable
local local_val="local one"

# If variable default_value is not set, set it to "example default value" and assign again.
default_value=${default_value:="example default value"}
  • If {}(parameter expansion) is not used, then variable test5678 is used and variable test is not used like below.
test=1234
echo "This is $test5678" # "This is "

echo "This is ${test}5678" # "This is 12345678"
  • If not wrapped with "", then unary operator expected error can be comes out.
  • Because its form is substitution so it is changed to if [ == " " ]
blank=" "
if [ ${blank} == " " ]
then
        echo "blank test"
fi


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