首页 > 解决方案 > 为什么我无法通过这个 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

标签: linuxshell

解决方案


那是因为你使用'$VAR'而不是"$VAR"在你的if. 试试"$VAR"吧。内$VAR单引号 ( '') 将被解释为普通字符串,不会解析为您的变量。

要查看差异,请尝试以下操作:

input          output
-------------- --------------------------------------------------
echo "$VAR"    /home/<your_username>/MyShellScripts/sample.txt
echo '$VAR'    $VAR

推荐阅读