大网数据广告活动
服务器运维问答

How to keep script from swallowing all of stdin?

· 52CE 我爱测

I have a script that reads from a pipe in a loop and runs an expect script and a normal shell script in the loop. Both scripts run ssh to another server to grab a piece of data. For example: cat /tmp/file | while read a b c d do …

问题原文

原帖链接 · Justin · CC BY-SA 3.0

I have a script that reads from a pipe in a loop and runs an expect script and a normal shell script in the loop. Both scripts run ssh to another server to grab a piece of data. For example:

cat /tmp/file |
while read a b c d
do
   s=`expect-script server1 $b`
   c=`ssh $b normal-script`
   echo $s $c
done

Even though there are many lines in /tmp/file, the script quits after processing the first line. I suspect that the expect script is swallowing all of stdin so that when it returns, there is nothing left to read. How can I avoid this? I don't want any of the scripts I call to read from the stdin of the main script.

社区高分解答

原帖链接 · glenn jackman · CC BY-SA 3.0

It's actually ssh that's slurping up stdin. Just add the -n option:

    c=$( ssh -n $b normal-script )

If you don't want to do that, you can have your shell while loop read from a different file descriptor, leaving stdin untouched:

while read -u3 a b c d
do
    s=$( expect-script server1 $b )
    c=$( ssh $b normal-script )
    echo $s $c
done 3< /tmp/file

(assuming bash/ksh/zsh for the read -u option)

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2014-06-21)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。