【发布时间】:2012-03-09 13:58:41
【问题描述】:
我正在尝试使用 bash 检查文件是否存在。这是我的代码
if [-e file.txt]; then
echo "file exists"
else
echo "file doesn't exist"
fi
但是当我运行它时,我得到:
./test.sh: line 3: [-e: command not found
我做错了什么?
【问题讨论】:
标签: bash
我正在尝试使用 bash 检查文件是否存在。这是我的代码
if [-e file.txt]; then
echo "file exists"
else
echo "file doesn't exist"
fi
但是当我运行它时,我得到:
./test.sh: line 3: [-e: command not found
我做错了什么?
【问题讨论】:
标签: bash
[ 不是 Bash 中的特殊标记;只是 word [ 是一个内置命令(就像 echo 一样)。所以你需要一个空格。同样,] 之前需要一个空格:
if [ -e file.txt ] ; then
也就是说,我建议改为 [[ ]] — 它在某些方面更安全(尽管它仍然需要空格):
if [[ -e file.txt ]] ; then
【讨论】:
[[ 是 bash 功能,因此您不能使用 /bin/sh 调用脚本
糟糕,我需要在[ 和-e 之间留一个空格。像这样:
if [ -e file.txt ]; then
echo "file exists"
else
echo "file doesn't exist"
fi
【讨论】:
if [ -e file.txt ]; then
你需要空格。 [ 和 ] 是常规程序。
【讨论】:
] 不是程序,它是[ 命令所需的最后一个参数
'[' 和 ']' 需要是 'on--their-own',即被空格包围。
if [ -e file.txt ] *emphasized text*; then
echo "file exists"
else
echo "file doesn't exist"
fi
【讨论】: