0

The script is called isFile.sh and looks like this:

#!/bin/sh

echo $1
echo $2

if [ ! -f $1 ]; then
  echo "$1 (arg1) is not a file"
fi

if [ ! -f $2 ]; then
  echo "$2 (arg2) is not a file"
fi

First I created a file by doing touch file.exist.

And I ran bash isFile.sh file.exist file.notexist The output was:

file.exist

file.notexist

file.notexist (arg2) is not a file


Then I ran bash isFile.sh "" file.notexist The output was:

(# empty line)

file.notexist

file.notexist (arg2) is not a file

Expected output is:

(# empty line)

file.notexist

(arg1) is not a file

file.notexist (arg2) is not a file

Can somebody explain why?

SoloKyo
  • 41
  • 1
  • 5

1 Answers1

7

The issue is that [ ! -f $1 ] becomes [ ! -f ] after expansion (and not [ ! -f "" ] as you thought!), so instead if checking if a given file exists, [ checks if the -f string is empty or not. It's not empty, but thanks to ! the final exit code is 1, thus the echo command is not executed.

That's why you need to quote your variables in POSIX shells.

Related questions:

nxnev
  • 3,634
  • 2
  • 12
  • 28
  • Thanks for mention me add quotes on variables, but still I can't get the output right. Means I still get the same output after I double quoted my variable in the IF condition. Change $1 to " " or ' ' doesn't work either. – SoloKyo Aug 07 '18 at 05:16
  • @KitisinKyo, do you mean that `bash -c '[ -f "" ] && echo yes'` outputs `yes` for you? What system is that? – Stéphane Chazelas Aug 07 '18 at 05:37
  • @Stéphane Chazelas, Nope, `bash -c '[ -f "" ] && echo yes'` had no output. I'm using CentOS 7 – SoloKyo Aug 07 '18 at 05:58
  • @KitisinKyo, yet you're saying in the comment above that `if [ ! -f "" ]; then echo ...; fi` outputs nothing. Try running the script with `bash -x` to see what happens. – Stéphane Chazelas Aug 07 '18 at 06:00
  • @Stéphane Chazelas, I edited a wrong script, the code worked, I was dumb. – SoloKyo Aug 07 '18 at 06:13
  • @KitisinKyo If this answer solved the problem please consider [accepting it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). Or add your own answer if the actual solution differs from this one. That way other users with similar problems may benefit from it. – nxnev Aug 07 '18 at 06:24