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