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.

$ ./ test1 test2

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

The script would output the following text.


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?

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

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


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

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


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
OPTIONC: d option

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


Leave a Reply

Your email address will not be published.