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

后端 未结 20 2466
深忆病人
深忆病人 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条回答
  • 2020-11-22 11:36

    It's worth mentioning that if you need to execute a single command you can abbreviate

    if [ ! -f "$file" ]; then
        echo "$file"
    fi
    

    to

    test -f "$file" || echo "$file"
    

    or

    [ -f "$file" ] || echo "$file"
    
    0 讨论(0)
  • 2020-11-22 11:36

    To reverse a test, use "!". That is equivalent to the "not" logical operator in other languages. Try this:

    if [ ! -f /tmp/foo.txt ];
    then
        echo "File not found!"
    fi
    

    Or written in a slightly different way:

    if [ ! -f /tmp/foo.txt ]
        then echo "File not found!"
    fi
    

    Or you could use:

    if ! [ -f /tmp/foo.txt ]
        then echo "File not found!"
    fi
    

    Or, presing all together:

    if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi
    

    Which may be written (using then "and" operator: &&) as:

    [ ! -f /tmp/foo.txt ] && echo "File not found!"
    

    Which looks shorter like this:

    [ -f /tmp/foo.txt ] || echo "File not found!"
    
    0 讨论(0)
提交回复
热议问题