意図

意図

意図


私は小さなシェルスクリプト(POSIXを除くsystem_beep())を書いています。

Cygwinで実行されているこのスクリプトは、母親のラップトップがオフになっていることを確認して明確な結果を提供し、オンになっているとビープ音を5回鳴らします。

パスワード


#!/bin/bash

set -o nounset

blink=$(tput blink)
bold=$(tput bold)
reverse=$(tput rev)
no_color=$(tput sgr0)

red=$(tput setaf 1)
#blue=$(tput setaf 4)
#cyan=$(tput setaf 6)
green=$(tput setaf 2)
#white=$(tput setaf 7)
#yellow=$(tput setaf 3)
#magenta=$(tput setaf 5)

lid_open_color="${blink}${bold}${reverse}${red}"
lid_closed_color="${blink}${bold}${reverse}${green}"

system_beep()
{
    echo -ne '\007'
}

beep_x_times()
{
    i=1; while [ "$i" -le "$1" ]; do

        i=$((i + 1))
        system_beep
        sleep 1s

    done
}

get_lid_state_mom()
{
    if ! ssh heruser@laptop_ip -p port_number -o ConnectTimeout=3 -i /home/myuser/.ssh/id_rsa 2> /dev/null \
        cat /proc/acpi/button/lid/LID0/state | awk '{print $2}'; then

#    if [ "$?" -ne 0 ]; then

        echo "Error connecting to Mom via SSH"
        exit 1

    fi

}

state=$(get_lid_state_mom)



if [ "$state" = "closed" ]; then

    echo "${lid_closed_color}closed${no_color}"

elif [ "$state" = "open" ]; then

    echo "${lid_open_color}open${no_color}"
    beep_x_times 5

else

    echo "Some error occurred!"

fi

質問

努力にもかかわらず、次のような結果が出る理由を理解できないようです。

$ ./lid-status-mama-beep
Some error occurred!

正常に動作してもSSH経由でラップトップを接続できる場合:

ふたが閉じている場合:

$ ./lid-status-mama-beep
closed

ふたが開いている場合:

$ ./lid-status-mama-beep
open

このエラー処理ケースでは、明らかに何か間違ったことをしています。


質問

このスクリプトを出力するには:

Error connecting to Mom via SSH

何らかの理由で接続が切断された場合?

ベストアンサー1

解決策

各行の説明についてはコメントをご覧ください。

get_lid_state_mom()
{
    # I have omitted awk completely here, getting raw value instead
    ssh -p port_number -o ConnectTimeout=3 -i /home/myuser/.ssh/id_rsa heruser@laptop_ip cat /proc/acpi/button/lid/LID0/state 2> /dev/null
}

# this had to be renamed in order for me to know it is a raw value
lid_state_raw=$(get_lid_state_mom)

# indirect test for successful execution seems to be the best method
if [ "$?" -ne 0 ]; then

    echo "Error connecting to Mom via SSH"
    exit 1

fi

# after the success extract the state from the raw value
lid_state=$(echo "$lid_state_raw" | awk '{print $2}')

おすすめ記事