shell脚本判断文件是否存在

2025-03-22 15:19:17
推荐回答(2个)
回答1:

if [ -f file.txt ]; then
   echo "File exists!"
else
   echo "File not exist!"
fi

 用-e或-f判断都行。-f还顺带检查是否是文件。

回答2:

#!/bin/bash
if [ -f $1 ]
then
echo "$1 exists!"

else
echo "$1 not exists!"

fi

***********************
运行
bash test.sh /home/user.txt
记得这个要加绝对路径~~~,在运行的时候,脚本后面接一个文件参数~~~