如果语句不能通过 bash 脚本工作,但可以在 cli 上工作,为什么?

问题描述 投票:0回答:1

任何人都可以帮助我吗

for f in $(grep -Ev '^(#|$)' $(readlink -f $(git config --get core.excludesfile)) | awk '{$1=$1};1' | tr -d '\r' ); do for g in $(git ls-files --others --ignored --exclude-standard); do if [ $f == $g ]; then echo "ok $f $g"; fi; ls $f; done; done

我正在测试上面的脚本,当我直接在 bash cli 上执行它时,它按预期工作,但是当我通过脚本执行它时,它不起作用。主要是 if 语句没有被执行,任何人都可以告诉我原因或任何替代方案吗?

我尝试了不同的东西,比如带上

shopt
并主要对 if 语句进行操作,每次在 cli 上它都可以工作,但使用脚本则不行!

这是从单行代码转换而来的代码:

for f in $(grep -Ev '^(#|$)' $(readlink -f $(git config --get core.excludesfile)) | awk '{$1=$1};1' | tr -d '\r' ); do 
    for g in $(git ls-files --others --ignored --exclude-standard); do
        if [ $f == $g ]; then 
            echo "ok $f $g"
        fi 
        ls $f
    done
done

linux bash shell if-statement conditional-formatting
1个回答
0
投票

您的 for 循环是一种反模式,请使用 while IFS= read -r 循环,而不是参见 https://mywiki.wooledge.org/BashFAQ/001。还有各种其他问题 http://shellcheck.net 可以帮助您解决您的脚本当前将根据环境设置、运行脚本的目录内容、运行脚本的文件名称执行各种不同的操作,等等

这可能就是您想要做的,如果没有示例输入和预期输出,很难判断:

#!/usr/bin/env bash

declare -A gitLsFiles
while IFS= read -r file; do
    gitLsFiles["$file"]=1
done < <(git ls-files --others --ignored --exclude-standard)

while IFS= read -r file; do
    if [[ -v gitLsFiles["$file"] ]]; then
        echo "ok $file $file"
    fi
    ls "$file"
done < <(
    git config --get core.excludesfile |
        awk '!/^(#|$)/ { $1=$1; gsub(/\r/,""); print }'
)
© www.soinside.com 2019 - 2024. All rights reserved.