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

前端 未结 4 614
有刺的猬
有刺的猬 2021-01-18 18:46

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


        
相关标签:
4条回答
  • 2021-01-18 19:02

    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
    
    0 讨论(0)
  • 2021-01-18 19:03

    the '[' and ']' needs to be 'on--their-own', i.e. surrounded by spaces.

    if [ -e file.txt ] *emphasized text*; then
      echo "file exists"
    else
      echo "file doesn't exist"
    fi
    
    0 讨论(0)
  • 2021-01-18 19:06

    [ 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
    
    0 讨论(0)
  • 2021-01-18 19:10
    if [ -e file.txt ]; then
    

    You need spaces. [ and ] are regular programs.

    0 讨论(0)
提交回复
热议问题