変数がnullである場合に予想される整数式を変更する

変数がnullである場合に予想される整数式を変更する

タイトル、年、シーズン、エピソード番号に基づいてファイル名を作成するために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

おすすめ記事