gpt4 book ai didi

bash - ' ]' expected Bash syntax error - despite ` ]` 存在并被空格包围

转载 作者:行者123 更新时间:2023-11-29 09:42:41 25 4
gpt4 key购买 nike

运行我的 bash 脚本时,出现以下错误:

./myscript.sh:[:16: ']' expected

第 16 行是:

    [ -d "$dir" ] && echo "$dir" && for file in "$dir"/*/*

通常错误来自 [] 中缺少空格条件,但我没有忘记。这是从第 14 行开始的其余脚本:

for dir in "$message_directory"/*
do
[ -d "$dir" ] && echo "$dir" && for file in "$dir"/*/*
do
if [ -d "$file" ] ; then
if [[ -f "$file"/Message.txt || -f "$file"/Message.html ]] ; then
hashMD5=$(md5sum "$file/message"* | cut -d " " -f1 | head -n 1)
todelete=$(find "$directory_to_check" -type f -not -path "*$message_directory*" -name "Message*" -exec md5sum "{}" \; | grep "^$hashMD5" )
todelete=$(echo "$todelete" | tr -s " " | cut -d " " -f2-)
todelete=$(echo "$todelete" | sed -E 's/(Message[0-9][0-9]*).+/\1/' )
if [[ ! -z "$todelete" ]] ; then
echo "searching for hash : $hashMD5"
while read -r line; do
message_todelete=$(echo "$line")
echo "I will delete : $message_todelete"
md5sum "$todelete/Message"* | head -n 1
#rm -r "$line"
done <<< "$todelete"
fi
fi

fi
done
done

我尝试使用 dash 运行脚本它一直工作到 <<<满足了,这可以理解,但是没有关于缺少]的错误

最佳答案

您的错误源于 Unicode 在结束 ] 之后出现空格(在非 ASCII 范围内) ,特别是 NO-BREAK SPACE Unicode 字符 (Unicode U+00A0)。

Bash 不识别这样的空格,这就是为什么它找不到结束符 ] 的原因.[1]

您可以按如下方式验证:

LC_ALL=C cat -et myscript.sh

将非 ASCII 字符显示为元键组合。
Unicode 不间断空格显示为 M-BM- .

顺便说一句,当 SO 呈现问题中的代码时,这些不间断空格会转换为常规空格,因此复制和粘贴您的代码不会揭示问题- 只检查问题的源代码


如果您想将 UTF-8 编码文件中的非 ASCII 空格和标点符号自动翻译成最接近的 ASCII 等价物,您可以使用我的 nws (空白规范化)CLI;例如:
nws --ascii -i.bak myscript.sh .
nws可以安装via the npm registry通过执行 [sudo] npm install -g nws-cli ,或手动从 repository .


[1] []必须用 whitespace 与周围的元素分开,以便 Bash 将其识别为语法元素。在这种情况下,Bash 看到了单词 ]<no-break-space> , 因为从 Bash 的角度来看,不间断空间不是空白,所以没有关闭 ]被发现。

关于bash - ' ]' expected Bash syntax error - despite ` ]` 存在并被空格包围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39959834/

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