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?
$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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With