修復變數可以為空時預期的整數表達式

修復變數可以為空時預期的整數表達式

我正在嘗試使用 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

相關內容