1

When i use the following code i would expect bash to iterate over each command line defined in $SSHCMDS. It does so as long i do not use a function that calls SSH with the command.

Any ideas why this loop breaks after the first command?

Current output:
$ ./test.sh 
NoExec: id root
NoExec: date
NoExec: uname
NoExec: notexistingcommand
WithExec: id root
Greetings from inside execmd. CMD is: id root
uid=0(root) gid=0(root) groups=0(root)

Expected output:
$ ./test.sh 
NoExec: id root
NoExec: date
NoExec: uname
NoExec: notexistingcommand
WithExec: id root
Greetings from inside execmd. CMD is: id root
uid=0(root) gid=0(root) groups=0(root)
WithExec: id date
Greetings from inside execmd. CMD is: date
Sat Oct 7 13:06:41 CEST 2017
WithExec: id uname
Greetings from inside execmd. CMD is: uname
Linux
Greetings from inside execmd. CMD is: notexistingcommand
bash: notexistingcommand: command not found
Error executing command!
#!/bin/bash

IP="127.0.0.1"
USER="root"

function execmd {
    echo "Greetings from inside execmd. CMD is: $1"
    local SSHRESULT
    SSHRESULT=$(ssh $USER@$IP "$1")
    if [ $? -ne 0 ]; then
    echo "Error executing command!"
    exit 1
    fi
    echo $SSHRESULT
}

SSHCMDS="id root
date
uname
notexistingcommand"

# nossh
printf '%s\n' "$SSHCMDS" | while IFS= read -r CMD
do
    echo "NoExec:" "$CMD"
done

# withssh
printf '%s\n' "$SSHCMDS" | while IFS= read -r CMD
do
    echo "WithExec:" "$CMD"
    execmd "$CMD"
done

codeforester
  • 39,467
  • 16
  • 112
  • 140
Birt
  • 437
  • 1
  • 6
  • 11
  • 3
    It's because `ssh` is reading from the stdin (which is the output of `printf`). Add `-n` flag to `ssh` and you will be fine. See this post: https://stackoverflow.com/questions/41250439/read-r-doesnt-read-beyond-first-line-in-a-loop-that-does-ssh – codeforester Oct 07 '17 at 15:34
  • 1
    *+1* for asking a SSH question that's actually about programming or development. – jww Oct 07 '17 at 16:01

0 Answers0