シンプルなbashスクリプト用のシンプルなGUIの作成

シンプルなbashスクリプト用のシンプルなGUIの作成

「http」で始まるURLアドレスのリストに関連するいくつかのシステム変更を実行するbashスクリプトがあり、そのためのGUIを作成しようとしています。

私はこれの最後の部分に立ち往生しています:


changes="$(cat /home/$USER/.updates.log | grep http)"
if [ "$changes" != 0 ]; then
    zenity --question --text "Changes found in:\n$changes\n\nWould you like to update now?"
        if [ $? = 0 ]
        then
# password
sudo_password="$(gksudo --print-pass --description 'MyScript' -- : 2>/dev/null)"
# check for null entry or cancellation
if [[ ${?} != 0 || -z ${sudo_password} ]]
then
    exit 4
fi
if ! sudo -kSp '' [ 1 ] <<<"${sudo_password}" 2>/dev/null
then
    exit 4
fi
# notify
notify-send "Applying updates..." -i gtk-dialog-info -t 1000 -u normal &
# proceed to update
cuser="${SUDO_USER:-$USER}"
sudo -Sp ''  sudo /usr/local/bin/MyScript <<<"${sudo_password}"
# option to view log
new_update="$(cat /home/$USER/.updates.log | grep 'MyScript completed at ' | awk -F ' at ' '{print $2}')"
zenity --question --text "MyScript updated at $new_update\n\nWould you like to view the log file now?"
if [ $? = 0 ]
then
# display log
    zenity --text-info --filename=/home/$USER/.updates.log --width 680 --height 680
fi
fi
fi

実際、私にとって難しい部分は次のとおりです。

if [ "$changes" != 0 ]; then

ファイルに「http」で始まる行が含まれていない場合は、「更新が見つかりませんでした。終了中...」などのメッセージを表示したいのですが、zenityの問題ダイアログボックスに空の行を作成するだけです。この行を修正して「else」の下に別のコマンドを追加する必要があるようですが、どのように、どこにいるのかわかりません...

ベストアンサー1

必要なデータがないか、それが何をしているのかわからないので、スクリプトの残りの部分をテストすることはできませんが、次の行は間違いなく間違っています。

changes="$(cat /home/$USER/.updates.log | grep http)"

これは保存されます出力grep$changes文字列が見つかった回数ではなく、返された実際の行数です。たとえば、

$ cat file 
one http
two http
three http
$ changes=$(cat file | grep http)
$ echo "$changes" 
one http two http three http

上記のように、$changesファイル内の一致する各行は単に変数にリンクされます。必要なものは次のとおりです(catところで、grepファイル名を入力として使用する必要はありません)。

$ changes=$(grep -c http file)
$ echo $changes 
3

このスイッチを使用すると、行自体ではなく一致する行の数が印刷さ-cれます。grepあるいは、出力を渡してwc -l行数を計算することもできます。

changes=$(grep http file | wc -l)

どちらにしても大丈夫です。これで0より大きいことを確認できます$changes

if [ "$changes" -gt 0 ]]; then 
        ...
fi

変更を表示するには、元の方法を使用しますが、ゼロと比較しないでください。代わりに-z変数が空であることを確認する方法を使用してください。

changes=$(grep http /home/$USER/.updates.log)
## If $changes is empty
if [ -z "$changes" ]
then
     notify-send "Found no updates; exiting..." -i gtk-dialog-info -t 1000 -u normal &
     exit
else
     zenity --question --text "Changes found in:\n$changes\n\nWould you like to update now?"
    ...
fi

おすすめ記事