You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在父Shell脚本调用子Shell脚本时自动传递输入

解决Shell脚本嵌套调用时的输入传递问题

核心默认行为

子进程会自动继承父进程的标准输入(stdin)。如果你的input.txt里按顺序包含了script1.sh和script2.sh需要的输入内容,直接执行./script1.sh < input.txt就会把剩余输入自动传给script2.sh。

比如input.txt内容如下:

y
n

script1.sh读取第一行的y完成自身交互,调用script2.sh时,script2.sh会自动读取第二行的n。


进阶解决方案(默认行为不满足时)

如果script1.sh会把stdin内容全部读完,或者需要重复使用输入内容,可选用以下两种方法:

方法1:显式指定子脚本的输入源

在script1.sh里调用script2.sh时,直接重定向到目标输入文件:

# script1.sh中的调用代码
./script2.sh < input.txt

这种方式简单直接,但缺点是需要硬编码输入文件路径,灵活性较差。

方法2:保存父进程stdin供子进程复用

在script1.sh开头先把原始stdin保存到自定义文件描述符,调用子脚本时再复用该描述符,无需硬编码文件名:

#!/bin/bash
# 将原始stdin保存到文件描述符3
exec 3<&0

# script1.sh自身的交互逻辑
echo "Executing ....."
read -p "Do you want to continue (y/n)?" ans
echo "You chose: $ans"

# 调用script2.sh时,复用保存的原始stdin
./script2.sh <&3

# 可选:脚本结束前关闭文件描述符(系统会自动回收,可省略)
exec 3<&-

执行./script1.sh < input.txt后,script2.sh就能读取到input.txt的完整内容,不受script1.sh读取操作的影响。

内容的提问来源于stack exchange,提问作者dvrsandeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:40:14