OStack程序员社区-中国程序员成长平台

标题: How do I tell if a regular file does not exist in Bash? [打印本页]

作者: 菜鸟教程小白    时间: 2022-4-23 21:06
标题: How do I tell if a regular file does not exist in Bash?

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 $FILE does not exist."
fi

What's the correct syntax to use if I only want to check if the file does not exist?

#!/bin/bash

FILE=$1     
if [ $FILE does not exist ]; then
   echo "File $FILE does not exist."
fi


Best Answer-推荐答案


The test command ([ here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:

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





欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) Powered by Discuz! X3.4