当我使用以下代码时,我希望bash迭代$ SSHCMDS中定义的每个命令行。只要我不使用,它就会这样做 使用命令调用SSH的函数。
在第一个命令之后,为什么这个循环会中断?
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