4

I have written a little function that exits if the value of the function argument is empty, I would like to be able to also print the name of the parameter (not the value!) if it is possible, my following implementation fails to print the name of the parameter.

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

when called like so

exitIfEmpty someKey

should print

Exiting because someKey is empty
  • Wait, when you give it "someKey", $1 won't be empty. If it's empty, there's nothing to print. – choroba Mar 26 at 15:08
  • @choroba I want to print the parameter name if possible not its value. – Xerxes Mar 26 at 15:09
  • 1
    What do you mean by the name? Function arguments don't have names. – choroba Mar 26 at 15:32
13

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
  • Also: : "${!1:?Variable $1 is empty or unset}". – Kusalananda Mar 27 at 10:16
3

Pass the name as second argument

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

exitIfEmpty "$someKey" someKey
2
echo "Exiting because \$1 is empty"

should do the trick.

  • 3
    Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful. – ilkkachu Mar 26 at 15:30
  • ITYM echo 'Exit because $1 is empty' or echo "Exit because \$1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped – jimbobmcgee Mar 26 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.