很多时候,我们写Shell脚本的时候,需要下载文件、根据是否下载到文件后(文件是否存在)来判断下一步的操作。
在Bash里,可以使用test来判断文件/文件夹是否存在,格式如下
test EXPRESSION [ EXPRESSION ] [[ EXPRESSION ]]
两个括号会比较常用,不过都可以试试
检查文件是否存在
FILE=/opt/test.txt
if [ -f "$FILE" ]; then
    echo "$FILE exists."
fi
#if else
FILE=/opt/test.txt
if [ -f "$FILE" ]; then
    echo "$FILE exists."
else
    echo "$FILE does not exist."
fi
#两个括号
if [[ -f "$FILE" ]]; then 
    echo "$FILE exists."
fi
检查文件夹是否存在
使用 -d
FILE=/opt/test
if [ -d "$FILE" ]; then
    echo "$FILE is a directory."
fi
检查是否不存在
在前面加个感叹号 !
FILE=/opt/test.txt
if [ ! -f "$FILE" ]; then
    echo "$FILE does not exist."
fi

文章评论