我有以下代码来检测文件是否存在:
#!/bin/bash
VAR="/home/$USER/MyShellScripts/sample.txt"
if [ -e '$VAR' ]
then
echo "$VAR exist"
else
echo "the file $VAR doesn't exist!"
fi
if [ -x '$VAR' ]
then
echo "You have permissions to execute the file $VAR"
else
echo "You do not have permissions to execute the file $VAR"
fi
在指定目录上应用ls命令时,我看到:
MyLAPTOP:~/MyShellScripts$ ls
exercise_4.sh exercise_4Original.sh first.sh sample.txt second.sh
因此,如果文件存在于指定目录中,为什么未检测到该文件?脚本输出下方:
MyLAPTOP:~/MyShellScripts$ ./exercise_4.sh
the file /home/username/MyShellScripts/sample.txt doesn't exist!
You do not have permissions to execute the file /home/username/MyShellScripts/sample.txt
答案 0 :(得分:4)
那是因为您在'$VAR'
中使用"$VAR"
而不是if
。
尝试使用"$VAR"
。
单引号($VAR
)中的''
将被解释为普通字符串,而不是解析为您的变量。
要查看区别,请尝试以下操作:
input output
-------------- --------------------------------------------------
echo "$VAR" /home/<your_username>/MyShellScripts/sample.txt
echo '$VAR' $VAR
答案 1 :(得分:2)
``表示不扩展变量。
因此,此脚本检查名为'〜/ MyShellScripts / $ VAR'的文件。不是'“ /home//MyShellScripts/sample.txt”'
Test.sh:
#!/bin/bash
VAR="Test"
echo $VAR
echo "$VAR"
echo '$VAR'
结果:
$ ./Test.sh
Test
Test
$VAR