gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:23 26 4
gpt4 key购买 nike

我有以下代码来检测文件是否存在:

#!/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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com