タイトル、年、シーズン、エピソード番号に基づいて、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
これは、シーズンまたはエピソードが null でない場合は機能しますが、 null の場合はエラーが発生します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
シーズンの if ステートメントを 1 つのステートメントに結合します。次に、エピソードごとに繰り返します。
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