Shell / bash scripting

Shell is a commands interpreter. Implementations: sh, bash, zsh etc.

  • Variables

  • Conditional statements

  • Passing arguments to script

  • Read user input

  • Loops

  • Functions

#!/bin/sh - shebang line. Tells OS what shell program to use to execute script file. /bin/sh - actual location of the program.

Variables example

#!/bin/bash

echo "Setup and configure server"

file_name=config.yaml
config_files=$(ls config)

echo "using file $file_name to configure something"
echo "here are all configuration files: $config_files"

Conditional statement example

#!/bin/bash

echo "Setup and configure server"

# Check if we have the config directory
if [ -d "config" ]
then
  echo "reading config directory contents"
  config_files=$(ls config)
# elif can be used for more checks
else
  echo "config dir not found. Creating one"
  mkdir config
# End of the if/else statement
fi

Passing arguments to script

#!/bin/bash

param1=$1
param2=$2

echo "Provided parameters: $param1 and $param2"

Then we can run script in terminal: ./script.sh value1 value2 In this way we can provide up to 9 parameters.

$* - can be used to represent all arguments as a string. $# - total number of arguments provided.

Read user input

#!/bin/bash

read -p "Please enter your name: " user_name

echo "Provided name is: $user_name"

read -p - read from the prompt. Store input to the user_name variable.

Loops

#!/bin/bash

# for loop
for param in $*
  do
    echo $param
  done
  
# while loop
sum=0
while true 
do
  read -p "enter a score: " score
  if [ "$score" == "q" ]
  then
    break
  fi
  sum=$(($sum+$score))
  echo "total score: $sum"
done

$(( )) - double parenthesis for arithmetic operations.

Also in if statement we can see double brackets [[ ]] instead of single brackets. [] - POSIX. [[ ]] - BASH. Bash variant has more features, but we loose portability.

Functions

Function without parameters

#!/bin/bash

function score_sum {
  sum=0
  while true
  do
    read -p "enter a score: " score
    if [ "$score" == "q" ]
    then
      break
    fi
    sum=$(($sum+$score))
    echo "total score: $sum"
  done
}

score_sum

Function with parameters and return value

#!/bin/bash

function sum() {
  total=$(($1+$2))
  return $total
}

sum 2 10
result=$?

echo "sum of 2 and 10 is $result"

$? - captures value returned by last command.

Bash best practices

Last updated

Was this helpful?