スクリプトでロギングを開始しますが、スクリプト中にログファイル名を決定します。

スクリプトでロギングを開始しますが、スクリプト中にログファイル名を決定します。

スクリプトの途中で生成されたファイルに書き込むことができるbashスクリプト部分を作成する方法がわかりませんが(ユーザー入力によって異なるため)、出力を最初から作成したいと思います。

例:

#!/bin/bash
<start_of_logging>
<code>
 read -p "Enter your city: " city
 touch ${city}
<code>
<end_of_logging>

スクリプトはユーザーが入力した内容を知らないため、city正しい場合は<start_of_logging>そのセクションにログインできません。それとも回避策はありますか?私の言葉は、すべてを最初から記録し、ユーザーが提供した都市というファイルに記録したいという意味です。

ベストアンサー1

コメントを要約すると、コードは次のようになります。

#!/bin/bash
### start logging using temporary logfile
logfile="$(mktemp)" # possibly add options to mktemp, like "-p dir" as needed

# add a message to logfile
log()
{
    echo "$@" >> "$logfile"
}
### code
 read -p "Enter your city: " city
 touch ${city}
### update logfile
newlogfile="something_with_${city}.log"
log "renaming temporary logfile $logfile to $newlogfile"
mv "$logfile" "$newlogfile" && logfile="$newlogfile"
log "now logging to $logfile"
###

「testtown」と入力してスクリプトを実行すると、次のような結果が表示されます。

Enter your city: testtown
me@pc:~> cat something_with_testtown.log
renaming temporary logfile /tmp/tmp.alKCBTV7ti to something_with_testtown.log
now logging to something_with_testtown.log

重要なヒント

誰も:; rm -rf /都市(またはそのようなもの)に入らないことを願っています…

おすすめ記事