Print name if parameter passed to function

What gets passed to the function is just a string. If you run func somevar, what is passed is the string somevar. If you run func $somevar, what is passed is (the word-split) value of the variable somevar. Neither is a variable reference, a pointer or anything like that, they're just strings.

If you want to pass the name of a variable to a function, and then look at the value of that variable, you'll need to use a nameref (Bash 4.3 or later, IIRC), or an indirect reference ${!var}. ${!var} expands to the value of the variable whose name is stored in var.

So, you just have it the wrong way in the script, if you pass the name of a variable to function, use "${!1}" to get the value of the variable named in $1, and plain "$1" to get the name.

E.g. this will print variable bar is empty, exiting, and exit the shell:

#!/bin/bash
exitIfEmpty() {
    if [ -z "${!1}" ]; then
        echo "variable $1 is empty, exiting"
        exit 1
    fi
}
foo=x
unset bar
exitIfEmpty foo
exitIfEmpty bar

Pass the name as second argument

function exitIfEmpty()
{
        if [ -z "$1" ]
        then
        echo "Exiting because ${2} is empty"
        exit 1
        fi
}

exitIfEmpty "$someKey" someKey

echo "Exiting because \$1 is empty"

should do the trick.

Tags:

Bash