简体   繁体   中英

Checking if the first argument passed to a bash script is set?

I'm attempting to see whether the first argument passed to my script is set. I used the instructions found here to create a test: How to check if a variable is set in Bash?

Here's my script:

var=$1
if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi

Suppose I run it without any arguments:

ole@MKI:./test.sh
var is set to ''

Suppose I run it with an argument:

ole@MKI:./test.sh foo
var is set to 'foo'

In neither case does it report that the var is unset.

Thoughts?

TIA, Ole

The problem is with this line:

var=$1

This sets var and it does so regardless of whether $1 is set or not. The solution is to test $1 :

if [ -z ${1+x} ]; then echo "var is unset"; else echo "var is set to '$1'"; fi

This approach works:

$ test.sh
var is unset
$ test.sh a
var is set to 'a'

Even if no parameter is provided when the script is run, the var variable is set. It is assigned the empty string.

The shell also set the $# special parameter to the number of parameters.

Give a try to this:

if [[ $# = 0 ]] ; then printf "no parameter\n"; exit 1; else printf "At least one parameter\n"; var="${1}"; fi

If you go ahead with other additional parameters such as options, then you may consider to use the getopts - parse utility options - from The Open Group Base Specifications Issue 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM