`if[-e file.txt]`在bash中不工作
我正在尝试使用bash检查文件是否存在。这是我的密码`if[-e file.txt]`在bash中不工作,bash,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 我做错了什么 if [ -e file.txt ]; then 你需要空间。 [和]是常规节目。需要“[”和“]”独立运行,即被空格包围 if [ -e file.txt
if [-e file.txt]; then
echo "file exists"
else
echo "file doesn't exist"
fi
但当我运行它时,我得到:
./test.sh: line 3: [-e: command not found
我做错了什么
if [ -e file.txt ]; then
你需要空间。
[和]是常规节目。需要“[”和“]”独立运行,即被空格包围
if [ -e file.txt ] *emphasized text*; then
echo "file exists"
else
echo "file doesn't exist"
fi
[
在Bash中不是一个特殊的标记;只是单词[
是一个内置命令(就像echo
),所以它后面需要一个空格。同样,在]之前也需要一个空格
if [ -e file.txt ] ; then
也就是说,我建议改为[[]]
——它在几个方面更安全(尽管它仍然需要空格):
呜呜,原来我需要一个介于[
和-e
之间的空格。像这样:
if [ -e file.txt ]; then
echo "file exists"
else
echo "file doesn't exist"
fi
+1.请注意,[[
是一个bash功能,因此您不能使用/bin/sh调用脚本。请编辑您的答案以解释为什么双方括号更安全?学究一点,]
不是一个程序,它是[
命令所需的最后一个参数
if [ -e file.txt ]; then
echo "file exists"
else
echo "file doesn't exist"
fi