我正在尝试向我的代码添加一个等待点,然后可以手动恢复/解除阻塞。可悲的是,它没有按预期工作。我猜是由于heredoc的工作方式(=stdin)。
有人可以建议另一种仍在使用heredoc的替代方案,因为它可以使代码非常清晰或任何类似的语法服务于相同的目的。
username=root
host=blah
ssh -t $username@$host <<-EOF_REMOTE_BASH
## set options
set -x
printf ">>> Connected to %s@%s\n" "$username" "$host"
## loop and run logic
# this is sample loop only
for i in $(seq 1 2 20); do
## some code
# more code
# ...
# ...
# ...
## Wait until unblocked manually
# NOT WAITING!
read -s -n 1 -p "Press any key to continue . . ."
done
## Quit server
exit
EOF_REMOTE_BASH
编辑1:
username=root
host=blah
ssh -t $username@$host "$(cat<<-EOF_REMOTE_BASH
## prep file
src_file=/tmp/test
cat <<- 'EOF' > ${src_file}
10
20
30
EOF
## Loop over file, wait at each iteration
while IFS="" read -r line || [ -n "\$line" ]; do
echo "\$line"
read -s -n 1 -p "Press any key to continue . . ." && printf "\n"
done <"${src_file}"
EOF_REMOTE_BASH
)"
回答1
您正在尝试分配一个 tty (-t
) 但不从标准输入读取。这为解决方案提供了线索:
username=root
host=blah
ssh -t $username@$host '
## set options
set -x
printf ">>> Connected to %s@%s\n" "$username" "$host"
## loop and run logic
# this is sample loop only
for i in $(seq 1 2 20); do
## some code
# more code
# ...
# ...
# ...
## Wait until unblocked manually
# NOT WAITING!
read -s -n 1 -p "Press any key to continue . . ." </dev/tty
done
## Quit server
exit
'
保留heredoc的方法见:https://stackoverflow.com/q/1167746/10971581
然后你可以这样做:ssh -t $username@host "$cmds"
回答2
一种解决方法是将脚本作为 ssh 参数传递:
(如果您在脚本中定义变量,通常最好禁用带引号的扩展:'EOF_REMOTE_BASH'
,在这种情况下,您不要在脚本中引用变量:"\$line"
,删除 \)
ssh -t $username@$host "$(cat<<-'EOF_REMOTE_BASH'
read -s -n 1 -p "Press any key to continue . . ."
EOF_REMOTE_BASH
)"