There are 2 types of CLI or shelss that are used in Unix-based OS like Linux and macOS
Bash (Bourne-Again-SHell)
Shell
To check which shell program is currently running on your OS
echo $SHELL# use sh command to go to Bourne shellphuong@home:~$sh$
Scripting 101
Var
Case-sensitive, lower-case and underscores.
Start with $. e.g $my_variable
no space trailing allow
# bad examplemy_var=hello-world# good examplemy_var=hello-world
Include variable in a string in bash, using curly braces
# include var in stringmkdir ${folder_name}_bk
Passing args
# argument start from 1, so the 1st arg is $1# assigning var to 1st argfolder_name=$1mkdir $foler_name
Input prompting
# read the input from command linereadfolder_namemkdir $folder_name# prompting user before readingread-p"Enter folder name:"folder_namemkdir $folder_name
Operations (expr)
# must have while space before and after = sign$expr6+39$expr6-33# using \ to escape the multiply sign$expr6 \* 318# only return decimal, not supporting floating point$expr10/33# to return floating point, using bc -l$expr10/3|bc-l3.333333
Double parentheses
Using double parenteses to perform arithmetic operations and comparation
Arithmetic operations
# no need to escape * using \ any more# no need to use expra=5b=10c=$((a+b))d=$((a*b))
Comparison
a=5b=10if ((a < b)); thenecho"a is less than b"fi
Flow control
Condition
a=5b=10# using double [[ ]] to check the conditionif [[a -lt b]]thenecho"a is less than b"elif [[a -gt b]]echo"a is greater than b"elseecho"a equal b"fi
Loop
For loop
for x in123doecho"do this $x time"done# or to loop 1 to 3for x in {1..3}doecho"do this $x time"done# using double bracketsfor (( x =1; x <=3; x++ ))doecho"do this $x time"done# loop through files in folderfor file in $(ls)doecho"Line count of $file is $(cat $file |wc-l)"done
Add the shebang line to the top of the script, so that even if the script is running from an unsupported shells, it will use the /bin/bash interpreter.
#!/bin/bash
Exit code
# exit code stored in $# 0: success$ls-la$echo $?0# >0: failure$lss$echo $?127# you can specify an exit code by using exit commandexit25
Function
Using function to break up large script to smaller one. 1 function only performs a task.
#!/bin/bashfunctionadd() { sum=$(( $1 + $2 ))# this statement like return statementecho $sum}result=$(add35)echo"The result is $result"
Best practices
Design for re-usable, avoid duplicate code
Should not require to be edited before running
Use command line arguments to pass inputs.
Always return approriate exit codes in your script (0: success, >0: failure)
The shebang is placed at the 1st line of the script.