修复变量可以为空时预期的整数表达式

修复变量可以为空时预期的整数表达式

我正在尝试使用 bash 脚本根据标题、年份、季节和集数创建文件名。

只有标题才能确保始终存在,因此我构建了以下代码:

title="A Title"
year=2019
source=null
resolution=null
season=null
episode=null

if [ "$year" == "null" ]; then year=""; else year=" ($year)"; fi
if [ "$source" == "null" ]; then source=""; fi
if [ "$season" == "null" ]; then season=""; fi
if [ "$season" -gt 10 ]; then season=" - S$season"; else season=" - S0$season"; fi
if [ "$episode" == "null" ]; then episode=""; fi
if [ "$episode" -gt 10 ]; then episode="E$episode"; else episode="E0$episode"; fi


touch "$title"${year:+"$year"}${season:+"$season"}${episode:+"$episode"}.file

当 season 或 Episode 不为 null 时,这有效,但当它为 null 时,它会给出 error integer expression expected

如何修复此错误并保持此代码的目标?

所需输出的示例:

A Title.file
A Title (2019).file
A Title - S01E20.file
A Title (2019) - S10E05.file

答案1

由于您使用的是 bash,因此只需算术表达式:

season=null
if ((season < 1)); then echo covid19
elif ((season < 2)); then echo trump2020
else echo '???'
fi

covid19

对于您的实际问题,您可以使用printf -v(并且可能还有许多其他更好的解决方案):

>>> cat ./script
#! /bin/bash
if ((year)); then printf -v year ' (%d)' "$year"; else year=; fi
if ((season)); then printf -v season ' - S%02d' "$season"; else season=; fi
if ((episode)); then printf -v episode 'E%02d' "$episode"; else episode=; fi
echo "$title$year$season$episode.file"

>>> export title='A Title'
>>> ./script
A Title.file
>>> year=2019 ./script
A Title (2019).file
>>> year=2019 season=3 ./script
A Title (2019) - S03.file
>>> year=2019 season=3 episode=9 ./script
A Title (2019) - S03E09.file
>>> year=2019 season=3 episode=11 ./script
A Title (2019) - S03E11.file
>>> season=3 episode=11 ./script
A title - S03E11.file

答案2

您的脚本正在尝试根据数字测试空字符串。

:-您可以通过在可能未设置或设置为空字符串的变量的扩展中使用默认值表达式 ( ) 来避免这种情况。

例如:

if [ ${season:-"0"} -gt 10 ]; then BLAH...; fi

由于您也在测试该单词,因此您还可以设置匹配时"null"的适当默认值,而不是将其设置为空字符串。0

答案3

您正在将非数字值分配给season

if [ "$season" == "null" ]; then season=""; fi

因此在您的下一个代码中,该值可能是一个空字符串,因此会出现错误。

在算术比较之前,您可以控制变量是否为数字,如果为空,则为 false:

if [[ "$season" =~ ^[0-9]+$ && "$season" -gt 10 ]]; then
  season=" - S$season"
elif [[ "$season" = "null" ]]; then
  season=" - S0"
fi

答案4

将您的 season if 语句合并到一个语句中。然后重复剧集。

if [ "$season" == "null" ]; then
   # you could also perform some other assignment here
   season="";
elif [ "$season" -gt 10 ]; then
   season=" - S$season";
else
   season=" - S0$season";
fi

相关内容