Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test whether a positional parameter is set in Bash?

I wonder why the test [[ ! -v 1 ]] fails no matter if I pass the 1st positional parameter to the function below:

shopt -os nounset

function foo {
  echo -n "$FUNCNAME: 1st positional parameter "
  [[ ! -v 1 ]] && echo "is missing." || echo is "\"$1\"."
}

I know there are other ways to test but why doesn't this particular test work?

like image 553
Tim Friske Avatar asked Dec 27 '22 14:12

Tim Friske


1 Answers

In this case, you want to check if the parameter is unset.

has_1() {
  if [[ -z "${1+present}" ]]; then 
    echo "no first param"
  else
    echo "given: $1"
  fi
}

The parameter expansion ${var+word} will return "word" only if the parameter is not unset -- i.e. if you pass an empty string, the function will indicate the first parameter is given.

like image 127
glenn jackman Avatar answered Jan 13 '23 14:01

glenn jackman