3

The following returns nothing:

which asdf

So why does the if statement get triggered here?

x=$(which asdf)
if [ -f $x ]; then echo "exists"; fi
Ishmael7
  • 172
  • 1
  • 10

3 Answers3

5

You didn't quote $x, so your test becomes [ -f ], which is true because -f is a non-empty string.

if [ -f "$x" ]; then
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 3
    @Amadan: Bash will complain about `[[ -f ]]` but it won't complain about a null or unset variable (quoted or not) or a null string, it will evaluate to `false`. `nullvar=""; [[ -f $nullvar ]]`, `unset unsetvar; [[ -f $unsetvar ]]`, `[[ -f "" ]]` and `[[ -f \ ]]` (that's two spaces after the backslash) all evaluate to `false` without an error. – Dennis Williamson Jul 23 '19 at 22:15
1

Though Chepner has given good solution, in case you want to look for an alternate approach then try following once.

which asdf 2>&1 >/dev/null && echo "exists"
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

Looks like you are trying to check if a command exists. It is better to use the command builtin instead of which in that context, like this:

if command -v asdf; then
    echo "exists"
fi

To learn more about command, try help command.

Related:

codeforester
  • 39,467
  • 16
  • 112
  • 140