gpt4 book ai didi

bash - 如何在 bash 脚本中正确使用 elif 与 && 和 -o

转载 作者:行者123 更新时间:2023-12-03 00:21:26 24 4
gpt4 key购买 nike

Bash 版本 4.4.20
Ubuntu 16.04

我需要比较我所拥有的特定项目的时间和延期。下面的内容与我尝试做的类似,但错误是相同的。我不确定错误到底在哪里,因为 shellcheck 没有产生错误。

#!/bin/bash
#

while read -r filename; do
extension="${filename##*.}"
if [ "$extension" == "zip" ] && [ "$filename" == "one.zip" ]; then
echo "Filename is $filename"
elif [ "$extension" == "zip" ] && [ "$filename" == "file_1.zip" ] -o [ "$filename" == "file_2.zip" ] -o [ "$filename" == "file_3.zip" ]; then
echo "Filename is $filename"
elif [ "$extension" == "csv" ] && [ "$filename" == "two.csv" ]; then
echo "Filename is $filename"
else
echo "Filename is $filename"
fi
done<fileList.txt

错误:

Filename is one.zip
check.sh: line 8: [: too many arguments
Filename is file_1.zip
check.sh: line 8: [: too many arguments
Filename is file_2.zip
check.sh: line 8: [: too many arguments
Filename is file_3.zip
Filename is two.csv
Filename is three.sql

最佳答案

使用模式匹配来发挥你的优势:

while IFS= read -r filename; do
if [[ "$filename" = one.zip ]; then
echo "Filename is $filename"
elif [[ "$filename" = file_[123].zip ]; then
echo "Filename is $filename"
elif [[ "$filename" = two.csv ]; then
echo "Filename is $filename"
else
echo "Filename is $filename"
fi
done < fileList.txt

一个case语句将在任何 POSIX shell 中工作,而不仅仅是支持 bash 的 shell -像[[ ... ]]命令。

while IFS= read -r filename; do
case $filename in
one.zip) echo "Filename is $filename" ;;
file_[123].zip) echo "..." ;;
two.csv) echo "..." ;;
*) echo "..." ;;
esac
done

要匹配年份范围(?),您可以使用

case $value in
200[0-9]|201[0-9]|202[0-1]) echo "Year between 2000 and 2021" ;;
esac

你不能像 [[ value = ... ]] 那样简单地做到这一点,自 |case 的一部分语句的语法,而不是模式中的交替运算符。相反,您需要多个匹配运算符:

if [[ $value = 200[0-9] || $value = 201[0-19] || $value = 202[0-1] ]]; then

关于bash - 如何在 bash 脚本中正确使用 elif 与 && 和 -o,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175333/

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