1

iF anyone could explain me what does below code means ("-z ${1+x}"), then i'll be glad. I have a portion of code and i'm trying to understand it. I know that it checks something with string but don't know what exactly.

if [ -z ${1+x} ]; then 
    error "Please provide some information" 1;
fi

Thansk in advance

1
  • 3
    explainshell.com/… - hover over the different parts to get detailed explanation Commented Feb 8, 2017 at 10:55

2 Answers 2

2

The [ ] construct performs tests. It returns 0 if the test is "true", and a non-zero value if the test is "false".

The -z test takes one argument, and returns "true" if the argument is an empty (zero-length) string.

The "${1+x}" expansion expands to a given value (x in this case, but you could put whatever you want there) if positional parameter 1 is set. It is set if it has been assigned a value (even if this value is an empty string), and unset otherwise. If the positional parameter is not set, the expansion produces an empty string.

Please note that it works on variable names too. You could use "${MYVAR+x}" for instance.

The whole if block will display an error message if no value has been passed as argument 1 to the script or function. But if an empty value has been passed (i.e. myscript ""), there will be no error message.

Sign up to request clarification or add additional context in comments.

Comments

1

Could be better explained with an example,

Case-1: foo is unset

unset foo

if [[ ${foo+isset} = isset ]]; then
  echo "foo is set..."
else
  echo "foo is not set..."
fi

Running it produces,

bash -x script.sh
+ unset foo
+ [[ '' = isset ]]
+ echo 'foo is not set...'
foo is not set...

Case-2: foo is set and empty

$ bash -x script.sh
+ foo=
+ [[ isset = isset ]]
+ echo 'foo is set...'
foo is set...

Case-3: foo is set and having a valid value,

$ bash -x script.sh
+ foo=something
+ [[ isset = isset ]]
+ echo 'foo is set...'
foo is set...

So what basically ${paramter+word} does is

The form expands to nothing if the parameter is unset or empty. If it is set, it does not expand to the parameter's value, but to some text you can specify:

So,

if [ -z ${1+x} ]; then

checks if positional parameter $1 is set to a value, in which case it would have been assigned a value x and the check the if [ -z 'x' ] would have failed, but if $1 is empty the expansion would be if [ -z '' ] which means the test asserted true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.