Skip to content

Bach Commands

Bash Script

Each script starts with

#!/bin/bash
The above line is used by the shell to decide which interpreter to run the rest of the script.

Control flow

For loop

# output: 1 4 16 64
for g_comm in 1 4 16 64; 
  do echo $g_comm 
done

If-else statement

if if [ $1 = 1 ]; then
  echo "1st machine."
elif if [ $1 = 2 ]; then
  echo "2nd machine."
else
  echo "3rd machine."
fi

Command logic

"A ; B"  # Run A and then B, regardless of success of A
"A && B" # Run B if A succeeded
"A || B" # Run B if A failed
"A &"    # Run A in background

Vairables

mathematics

my_var1=10                      # assign [my_var1] as 10
my_var2=$(expr $my_var1 / 4)    # divide [my_var1] by 4
echo $my_var1 $my_var2          # output: 10 2

date and time

DATE=`date +%Y-%m-%d`
TIME=`date +%T`
echo $DATE $TIME

Note

Bash commands are highly recommeded to use. By saving Bash file and using Git one would always be able to keep track of historical operations. This methods shall not only save plenty of time but also prevent potential unexpected problem.