linux - 为什么我无法使用此 linux shell 脚本检测文件是否存在?

标签 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

最佳答案

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

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

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

关于linux - 为什么我无法使用此 linux shell 脚本检测文件是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811353/

相关文章:

java - JUnit 示例程序编译但给出运行时错误

linux - SSH 服务器 - 获取 sshd 进程转发端口 #N 的 pid

objective-c - Cocotron 链接错误

shell - 如何从 Meson 脚本运行 shell 命令?

bash - 在shell中过滤出文件中匹配的记录

linux - 是否可以在 'if' 语句中传递多个命令?

python - 如何删除 cuInit 失败 : unknown error in CUDA (PyCuda)

linux - 如何在 python 2.7 中使用 ctypes 返回指针字符串

linux - 将base64数据转换为十进制

javascript - MongoDB shell : printing to console without a trailing newline?