すべてが待つのではなく、バックグラウンドで実行する必要があります。

すべてが待つのではなく、バックグラウンドで実行する必要があります。

私はユーザーからコマンドを受け取り、大規模なサーバーリストを実行し、単一のファイルに書き込むスクリプトを作成しました。作成が完了するとメールが送信されます。私の要件は、スクリプトがバックグラウンドで実行され、完了したら電子メールを送信する必要があることです。

私はこれを試しましたが、書き込みwait $PROC_ID &はバックグラウンドで行われ、電子メールは空のデータですぐに送信されます。データがファイルに書き込まれたら、バックグラウンドで待ってからメールをトリガーできますか?

コード出力:

The output can be monitored in /tmp/Servers_Output_list.csv .....................Please Be Patient
Mail will get triggered once completed

コードは次のとおりです。私のスクリプトの機能について言及しました。

for i in `cat $file_name`
    do
        ssh -q -o "StrictHostKeyChecking no" -o "NumberOfPasswordPrompts 0" -o ConnectTimeout=2 $i "echo -n $i;echo -n ",";$command3" 2>>/dev/null &
    done >> $file_save &
    PROC_ID=$!
    echo "                                                "
    echo " The output can be monitored in $file_save....................Please Be Patient"
    echo "Mail will get triggered once completed"
    echo "                                    "
    wait $PROC_ID
    while true; do
        if [ -s $PROC_ID ];then
            echo "$PROC_ID process running Please check"
        else
            mailx -s "Servers Command Output" -a $file_save  <my [email protected]>
            break;
        fi
done &
exit 0;
fi

ベストアンサー1

私が正しく理解したら、sshコマンドを実行して完了するのを待ってからバックグラウンドでメールを送信したいと思います。これは、sshとメールが完了する前にスクリプトが完了できることを意味します。

だから私は次の解決策を提案します。

#!/bin/bash

# Set to real file if you want "log output"
log_file=/dev/null

file_save=/whatever

command3=<some command here>

function exec_ssh
{
    for i in $(cat $file_name); do
        ssh -q -o "StrictHostKeyChecking no" -o "NumberOfPasswordPrompts 0" -o ConnectTimeout=2 $i "echo -n $i;echo -n ',';$1" 2>/dev/null &
    done >> $file_save
    wait
    mailx -s "Servers Command Output" -a $file_save  <my [email protected]>
}

# export function, so it is callable via nohup
export -f exec_ssh $command3

# clear file_save
>$file_save

# run exec_ssh in the background. 
# nohup keeps it running, even when this script terminates.
nohup exec_ssh &>$logfile &

# Inform user
echo " The output can be monitored in $file_save....................Please Be Patient"
echo "Mail will get triggered once completed"

exit 0

exec_ssh関数はすべての操作を実行し、バックグラウンドで実行されますnohup。これにより、端末が閉じていてもスクリプトが完了してもバックグラウンドジョブが実行され続けます。

ユーザーがシステムからログアウトしたときに何が起こるのかわかりません。

おすすめ記事