linux - 为什么我无法通过这个 linux shell 脚本检测文件是否存在?
问题描述
我有以下代码来检测文件是否存在:
#!/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
解决方案
那是因为你使用'$VAR'
而不是"$VAR"
在你的if
. 试试"$VAR"
吧。内$VAR
单引号 ( ''
) 将被解释为普通字符串,不会解析为您的变量。
要查看差异,请尝试以下操作:
input output
-------------- --------------------------------------------------
echo "$VAR" /home/<your_username>/MyShellScripts/sample.txt
echo '$VAR' $VAR
推荐阅读
- c++ - 如何在 C++ 中为多个类创建别名
- activiti - 具有候选组和候选用户的用户任务
- javascript - 隐藏环回模型中的嵌套属性
- android - java.lang.NoSuchMethodError:类 Landroid/support/v4/app/NotificationCompat$Builder 中没有直接方法 V;或其超类
- zend-framework - 在 mysql 中打开的超过 250 个连接在 zend 中出现奇怪的问题
- c# - HttpWebRequest 抛出错误 403 禁止
- python - 您可以在 Python 3.6 中的一行中创建多个变量吗
- nodes - RAFT 配置问题:如何从特定通道中删除节点,但保持它为其他通道提供服务
- javascript - 如何使用此 JQueryUI 可放置代码获得正确的 div?
- apache-nifi - Apache NiFi 替换文本处理器以使用控制字符作为分隔符