2

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!

misteralexander
  • 448
  • 2
  • 7
  • 19

2 Answers2

3

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" ].

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681