Building Bash Muscle (8)

Let’s look at a way to execute bash script from a file. When you write any script, you want to make it reusable by accepting parameters to your script. Here is how we can accomplish it in bash script.

echo $0
echo $1
echo $2

You would execute this script like the following on your terminal.

$ ./test.sh test1 test2

* Make sure to give execute permission to the script. (chmod +x test.sh)

The script would output the following text.

./zutte.sh
test1
test2

The $0 parameter shows the path to the currently executing script. This is an intrinsic variable that comes with bash script.

What if you want to use named parameters like the example below?

$ ./test.sh -v true -f 'my f option' -d 'd option'

Here is how you can script to receive the values in the script.

#!/bin/bash

set -e # errorexit
set -u # treats undfined variables as errors
set -o pipefail 

while getopts "f:v:d:" arg;
do
    case $arg in
        f) MYVARF=$OPTARG;;
        v) VERBOSE=$OPTARG;;
        d) OPTIOND=$OPTARG;;
        \?) echo "Invalid option -$OPTARG" >&2;;   
    esac
done

echo "MYVARF: $MYVARF"
echo "VERBOSE: $VERBOSE"
echo "OPTIONC: $OPTIOND"

We can use getopts to create named parameters in bash script. I prefer this way because the order of the parameters does not matter. Executing the script above would output text like the following.

MYVARF: my f option
VERBOSE: true
OPTIONC: d option

To recap, I have summarized how to parameterize bash script in a clean way using getopts.

 

Author: admin

A software engineer in greater Seattle area

Leave a Reply

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