public
Authored by avatar PotatoGim

[Bash] Run SSH and parsing output with FIFO

Edited
parsing_ssh_with_fifo.sh 1.57 KiB
#!/bin/bash

set -o nounset

WPIPE=wpipe
RPIPE=rpipe

trap "rm -f $WPIPE; rm -f $RPIPE" EXIT

if [ ! -p $WPIPE ]; then
    mkfifo $WPIPE
fi

if [ ! -p $RPIPE ]; then
    mkfifo $RPIPE
fi

exec 3<>$WPIPE 4<>$RPIPE

################################################################################

##### 프로세스 치환을 사용하는 경우

# STDIN을 5에 임시 저장하고, WPIPE를 0으로 사상
exec 5<&0 0<&3

# 1, 2를 RPIPE로 사상
exec 4< <( ssh root@192.168.0.1 \
                "echo - | cat > test.txt; \
                echo \"EXITED: \$?\"" 2>&1 )

# 0을 STDIN으로 복구
exec 0<&5

##### 백그라운드 프로세스를 사용하는 경우
ssh root@192.168.0.1 \
    "echo - | cat > test.txt; \
    echo \"EXITED: \$?\"" <&3 1>&4 2>&4

################################################################################

RUNNING=1;

shopt -s nocasematch

EXIT_PATTERN=EXITED
INFO_PATTERN='^(\*|\+|-)[[:space:]]+\[([0-9]+)\][[:space:]]+(.*)[[:space:]]+(.*)$'

while [ $RUNNING -eq 1 ];
do
    while read -r -t 0.5 -s line <&4;
    do
        echo $line;

        if [[ $line =~ $EXIT_PATTERN ]]; then
            RUNNING=0
        fi

        if [[ $line =~ $INFO_PATTERN ]]; then
            STAT=${BASH_REMATCH[1]}
            NUM=${BASH_REMATCH[2]}
            NAME=${BASH_REMATCH[3]}
            VER=${BASH_REMATCH[4]}

            if [[ $VER =~ $VERSION ]]; then
                echo "MATCHED: $VER"
                echo $NUM >&3
            fi
        fi
    done

    sleep 1;
done

echo "EXIT"

exit 0
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment