How do I tell if a regular file does not exist in Bash?

后端 未结 20 2707
深忆病人
深忆病人 2020-11-22 10:57

I\'ve used the following script to see if a file exists:

#!/bin/bash

FILE=$1     
if [ -f $FILE ]; then
   echo \"File $FILE exists.\"
else
   echo \"File $         


        
20条回答
  •  Happy的楠姐
    2020-11-22 11:20

    There are three distinct ways to do this:

    1. Negate the exit status with bash (no other answer has said this):

      if ! [ -e "$file" ]; then
          echo "file does not exist"
      fi
      

      Or:

      ! [ -e "$file" ] && echo "file does not exist"
      
    2. Negate the test inside the test command [ (that is the way most answers before have presented):

      if [ ! -e "$file" ]; then
          echo "file does not exist"
      fi
      

      Or:

      [ ! -e "$file" ] && echo "file does not exist"
      
    3. Act on the result of the test being negative (|| instead of &&):

      Only:

      [ -e "$file" ] || echo "file does not exist"
      

      This looks silly (IMO), don't use it unless your code has to be portable to the Bourne shell (like the /bin/sh of Solaris 10 or earlier) that lacked the pipeline negation operator (!):

      if [ -e "$file" ]; then
          :
      else
          echo "file does not exist"
      fi
      

提交回复
热议问题