misteralexander
misteralexander

Reputation: 488

IF with no test flags?

I don't understand how to read this properly. This is an IF statement without any kind of test flags, so I don't understand the logic ... help?

    #!/bin/bash
    get_user_input() {
      if [[ $1 ]]; then
        use_default=1
      else
        use_default=
      fi

I understand that this is a function. I understand that its calling for the first positional argument ($1), but I don't understand why its in an IF statement, if they aren't testing for anything.

I've been tasked to rewrite a script from a vendor, and they have stuff like this all over the place. I'm thinking that maybe they've just purposefully over complicated things for job security?

I appreciate the help!

Upvotes: 2

Views: 66

Answers (2)

chepner
chepner

Reputation: 531490

Better than using the if statement is to use the following parameter expansion:

use_default=${1:+1}

If $1 has a non-null value, use_default is set to 1; otherwise, it gets the null value resulting from the expansion of $1.

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74665

From man bash, under CONDITIONAL EXPRESSIONS:

string
-n string
    True if the length of string is non-zero.

So this is the same as [[ -n $1 ]] (though clearly less readable to those familiar with other shells). Personally, I would suggest that you use [[ -n $1 ]] to make the desired behaviour explicit.

If you're interested in making the script more portable, you should go for [ -n "$1" ].

Upvotes: 3

Related Questions