Pass empty variable in bash Pass empty variable in bash bash bash

Pass empty variable in bash


On the first case you call the script with testFunct param2. Hence, it understands param2 as the first parameter.

It is always recommendable to pass parameters within quotes to avoid this (and to be honest, for me it is cleaner this way). So you can call it

testFunct "$param1" "$param2"

So to pass an empty variable you say:

testFunct "" "$param2"

See an example:

Given this function:

function testFunc(){    echo "param #1 is -> $1"    echo "param #2 is -> $2"}

Let's call it in different ways:

$ testFunc "" "hello"    # first parameter is emptyparam #1 is -> param #2 is -> hello$ testFunc "hey" "hello"param #1 is -> heyparam #2 is -> hello


Another best practice is to check the number of parameters passed using $#.

However, this does not solve the problem of one empty parameter, how would you know if the param1 is empty or param2 is empty. Therefore both checks are good parctices.


One can add set -o nounset in the body a bash file to achieve the same effect as bash -u does.

#!/bin/bashset -o nounsetfunction testFunc(){    echo "param #1 is :" $1    echo "param #2 is :" $2}param1="param1"param2="param2"testFunc $param1 $param2