Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash file existence checking missing ] [closed]

Tags:

linux

bash

I am attempting a simple file existence check in my bash script:

FILE_TO_CHECK=/home/username/path/to/file

if [ ! -f $FILE_TO_CHECK]; #line 9 in actual script
then
    echo File not found.
fi

Seems simple enough to me, but I'm getting the following error and I don't know why:

/path/to/script: line 9: [: missing `]'

I'm not exactly a bash expert, but I was pretty sure a backtick is not necessary in this context. What gives?

like image 304
sigmabeta Avatar asked Mar 15 '14 17:03

sigmabeta


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is if [- Z in bash?

In both cases, the -z flag is a parameter to the bash's "test" built-in (a built-in is a command that is built-into the shell, it is not an external command). The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something.

How do you check if file does not exist in bash?

In order to check if a file does not exist using Bash, you have to use the “!” symbol followed by the “-f” option and the file that you want to check. Similarly, you can use shorter forms if you want to quickly check if a file does not exist directly in your terminal.

How do you check if a file already exists in bash?

Open the “testfile.sh” in any text editor. Then write the script, save it by pressing “save”. One way is to find a file by asking for a filename from the user in the terminal. Use “-f” to check the file's existence.


2 Answers

Missing space before the closing ].

You have to understand that [ is a command and everything following it, until the ;, are its arguments. Command [ expects its last argument to be ]. But if you omit the space, then ] becomes the last character of the previous argument.

It might seem that [ ] is part of the if syntax. It's not the case. if has to be followed by any command, and if evaluates its exit status.

if true; then foo; fi

In the above line true is a command too.

$ which true
/bin/true

true is a command with the sole purpose of always having a true (0) exit status.

like image 147
SzG Avatar answered Sep 28 '22 14:09

SzG


You could also try:

if (test ! -f $FILE_TO_CHECK);

or

if !(test -f $FILE_TO_CHECK);

as [ is a shorthand for the test command.

like image 38
myusuf Avatar answered Sep 28 '22 16:09

myusuf