Bash Scripting cheat sheet

Advertisements

Bash scripts are a very useful tool for developers, even though we usually have our preference for a language Java, C#, python, NodeJS, etc, sometimes there are tasks or processes where we don’t want to spend a lot of effort on implementing them in that language. On those case, probably, bash scripts comes to the rescue.

As a Full Stack Developer, sometimes I need to create bash scripts to automate some processes: interacting with the deployments, servers, and more. So, it’s important to have at hand some common command in bash.

Echo

echo "Hello World"

If/fi

if [[ $? -ne 0 ]]; then 
  ##Code here
fi  
  • Always ends the block with fi
  • Add spaces before and after the square brackets [[ , ]]
  • Add the ; then

If/else/fi

number=$?
if [[ $number -gt 0 ]]; then 
  ##Code here
else if [[ $number -eq 0 ]]; then
  ## Code here
else 
  ## Code here
fi  

Variables

my_var="Hello"
hello="World"
echo "Hi! $my_var $hello"

Methods

my_method () {
  param1=${1}
  param2=${2}
  echo "$param1 $param2"
}

my_method "Hello" "World"

Getting parameters

To get all the parameters $@ can be used.

To get a parameter by Index

param1=${1}
param2=${2}

By Index with default value

param1=${1-null}
param2=${2:-8000}

Debugging

set +x enables to print in the output all the instructions that are being executed

set +x 
## Code here 
set -x 

set -x (Default behavior) disables printing all the executed instructions in the output/console.

These options are helpful for debugging purposes. We can see which commands are being executed and determine the flow of the script in runtime.

Advertisements

Error Handling

set +e is used within the Bash to avoid stoping the execution instantly as a query exits while having a non-zero status.

set +e 
## Code here 
set -e 

2>/dev/null will filter out the errors so that they will not be output to your console

grep -i 'abc' content 2>/dev/null 

set -u and set +u enables and disables unset variables as an error and exit immediately. Unset variables are a common cause of bugs in shell scripts, so having unset variables cause an immediate exit is often highly desirable behavior.

Conditional Expressions

Conditional Expressions are code that can be added into a if [[ condition ]]

Strings

  • -n string: True, if the length of string is nonzero.
  • -z string: True, if the length of string is zero.
  • s1 = s2: True, if the strings s1 and s2 are identical.
  • s1 != s2:True, if the strings s1 and s2 are not identical.

Numbers

  • n1 -eq n2: True, if the integers n1 and n2 are algebraically equal.
  • n1 -ne n2: True, if the integers n1 and n2 are not algebraically equal.
  • n1 -gt n2: True, if the integer n1 is algebraically greater than the integer n2.
  • n1 -ge n2: True, if the integer n1 is algebraically greater than or equal to the integer n2.
  • n1 -lt n2: True, if the integer n1 is algebraically less than the integer n2.
  • n1 -le n2: True, if the integer n1 is algebraically less than or equal to the integer n2.

Yes/No Prompt

read -p "Do you want to blah..blah..blah (y/n)?" choice
  case "$choice" in
     y|Y ) 
       #DO here the YES logic
       ;;
     n|N ) 
       #DO here the NO logic
       ;;
     * ) 
       echo "Incorrect answer";;
  esac

Iterating folder content

parent_folder="/opt/"
for dir in "$parent_folder"/*/; do
    echo $dir
	only_name="$(basename "$dir")" #basename removes leading directories
    echo $only_name
done

Get parameters on Script

while getopts ":c:s:ha" opt; do
  case ${opt} in
    h ) #Do something when -h is indicated
      ;;
    a ) #Do something when -a is indicated 
      ;;
    c ) value_c="${OPTARG}" 
       ## Do something when -c <value_c> is indicated 
      ;; 
    s ) value_s="${OPTARG}" 
       ## Do something when -s <value_c> is indicated 
      ;;  

":c:s:ha" are the accepted flags. The ones with : after the flag letter accepts a parameter after the flag.

String Operations

Substring

MY_VAR="Hello World!"
MY_VAR2="${MY_VAR:0:7}"
echo "$MY_VAR2" #outputs "Hello W"

Remove Character

$ echo "hello, how are you?" | sed 's/h//' 
#Outputs "ello, how are you?" 
$ echo "hello, how are you?" | sed 's/h//g'
#Outputs "ello, ow are you?"

Handling outputs with AWK

awk is a scripting language used for manipulating data and generating reports.

There are a couple of special field identifiers. These represent the entire line of text and the last field in the line of text:

  • $0: Represents the entire line of text.
  • $1: Represents the first field.
  • $2: Represents the second field.
  • $7: Represents the seventh field.
  • $NF: Stands for “number of fields,” and represents the last field.
MY_OUTPUT="Adam	Gamboa Developer"
echo "$MY_OUTPUT" | awk '{print $1,$3}'
##prints "Adam Developer"

References

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *