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


echo $1
echo $2

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

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

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

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



file.notexist (arg2) is not a file

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

(# empty line)


file.notexist (arg2) is not a file

Expected output is:

(# empty line)


(arg1) is not a file

file.notexist (arg2) is not a file

Can somebody explain why?

  • Are you sure about echo$1? I would think it is echo $1 (better cut an paste). And welcome! – Volker Siegel Aug 7 '18 at 6:01
  • @ Volker Siegel, Sure it's echo $1, I edited my question, thanks. – SoloKyo Aug 7 '18 at 6:04

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:

  • 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 7 '18 at 5:16
  • @KitisinKyo, do you mean that bash -c '[ -f "" ] && echo yes' outputs yes for you? What system is that? – Stéphane Chazelas Aug 7 '18 at 5:37
  • @Stéphane Chazelas, Nope, bash -c '[ -f "" ] && echo yes' had no output. I'm using CentOS 7 – SoloKyo Aug 7 '18 at 5: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 7 '18 at 6:00
  • @Stéphane Chazelas, I edited a wrong script, the code worked, I was dumb. – SoloKyo Aug 7 '18 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.