Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`if [-e file.txt]` not working in bash

Tags:

bash

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?

like image 920
Eddy Avatar asked Mar 09 '12 13:03

Eddy


People also ask

What does if (- E mean in bash?

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.

How do you test if a 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.

What is $@ in bash?

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.

How do I negate if condition in shell script?

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.


2 Answers

[ 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
like image 84
ruakh Avatar answered Sep 18 '22 12:09

ruakh


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
like image 45
Eddy Avatar answered Sep 16 '22 12:09

Eddy