bashrc函数 -e文件检查始终为假

huangapple go评论73阅读模式
英文:

bashrc function -e file check is always false

问题

Bashrc函数接收一个文件名。即使我不使用变量,-e和/或-f检查始终返回false。

    FILE=/var/log/nginx/$1
    if [[ -e "$FILE" ]]; then
        echo "存在"
    else
        echo "不存在"
    fi
    sudo awk '{print $1}' /var/log/nginx/$1 | cut -d" " -f1 | sort | uniq | wc -l

后面的awk命令运行正常,但if语句始终为false。

这仍然返回false,awk命令仍然运行正常:

FILE=/var/log/nginx/dtb_access
if [[ -e $FILE ]]; then
    echo "存在"
else
    echo "不存在"
fi
sudo awk '{print $1}' $FILE | cut -d" " -f1 | sort | uniq | wc -l

**更新**

views() {
set -x
file=/var/log/nginx/$1
if [[ -e "$file" ]]; then
echo "存在"
else
echo "不存在"
fi
sudo awk '{print $1}' "$file" | cut -d" " -f1 | sort | uniq | wc -l
set +x
}

```views dtb_access```的输出:
  • file=/var/log/nginx/dtb_access
  • [[ -e /var/log/nginx/dtb_access ]]
  • echo 不存在
    不存在
  • wc -l
  • uniq
  • sort
  • cut '-d ' -f1
  • sudo awk '{print $1}' /var/log/nginx/dtb_access
    7
  • set +x

我尝试过将变量放在引号中和不放在引号中。我尝试过只使用静态字符串和没有变量,但每次结果都是一样的。
英文:

Bashrc function receives a filename. The -e and/or -f check always returns false, even if i don't use a variable.

FILE=/var/log/nginx/$1
if [[ -e "$FILE" ]]; then
        echo "exists"
else
        echo "not"
fi
sudo awk '{print $1}' /var/log/nginx/$1 | cut -d" " -f1 | sort | uniq | wc -l

The latter awk command works fine, but the if statement is always false.

This still returns false and the awk command still works:


    FILE=/var/log/nginx/dtb_access
    if [[ -e $FILE ]]; then
        echo "exists"
    else
        echo "not"
    fi
    sudo awk '{print $1}' $FILE | cut -d" " -f1 | sort | uniq | wc -l

update

views() {
    set -x
    file=/var/log/nginx/$1
    if [[ -e "$file" ]]; then
        echo "exists"
    else
        echo "not"
    fi
    sudo awk '{print $1}' "$file" | cut -d" " -f1 | sort | uniq | wc -l
    set +x
}


output of views dtb_access:

+ file=/var/log/nginx/dtb_access
+ [[ -e /var/log/nginx/dtb_access ]]
+ echo not
not
+ wc -l
+ uniq
+ sort
+ cut '-d ' -f1
+ sudo awk '{print $1}' /var/log/nginx/dtb_access
7
+ set +x

I've tried putting the variable in both types of quotations and none at all. I've tried just using a static string and no variable, every time it's the same outcome

答案1

得分: 2

尝试

文件="/var/log/nginx/dtb_access"
如果 sudo test -e "$文件"; then
echo "存在"
else
echo "不存在"
fi

sudo awk ...


因为运行脚本的用户可能无法访问 `/var/log/nginx`,因此 `-e` 失败。
英文:

Try

file="/var/log/nginx/dtb_access"
if sudo test -e "$file"; then
  echo "exists"
else
  echo "not"
fi

sudo awk ...

as the user running the script may not have access to /var/log/nginx and therefore -e fails.

huangapple
  • 本文由 发表于 2023年4月17日 07:48:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76030881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定