I'm trying to check if a file exists using bash. This is my code
if [-e file.txt]; then
echo "file exists"
else
echo "file doesn't exist"
fi
But when I run it I get:
./test.sh: line 3: [-e: command not found
What am I doing wrong?
The “if –e” and “if –s” are such operators in Bash, used for testing the existence of a file. The difference between the two is that the former only tests the existence of a file, whereas the latter also checks if there are any contents in that file or not.
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.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.
NegationWhen we use the not operator outside the [[, then it will execute the expression(s) inside [[ and negate the result. If the value of num equals 0, the expression returns true. But it's negated since we have used the not operator outside the double square brackets.
[
is not a special token in Bash; it's just that the word [
is a builtin command (just like echo
). So you need a space after it. And, similarly, you need a space before ]
:
if [ -e file.txt ] ; then
That said, I recommend [[ ]]
instead — it's safer in a few ways (though it still requires the spaces):
if [[ -e file.txt ]] ; then
Woops, turns out I needed a space between [
and -e
. Like this:
if [ -e file.txt ]; then
echo "file exists"
else
echo "file doesn't exist"
fi
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