如果脚本通过管道运行,请保留stdin



我有以下脚本,该脚本是在stdin中读取的,并将其打印出来:

#############
# myscript.sh
#############
#!/bin/sh
STDIN=$(less <&0 2>/dev/null)
echo $STDIN

如果运行"正常"/"预期"方式:

运行此脚本
echo Testing | ./myscript.sh 
Testing

但是,我需要以不同的方式运行它...即。将脚本存储在变量中并运行它。但是问题是,当我这样做时,我将失去stdin信息。

[root@ip-test]# thescript=$(cat ./myscript.sh)
[root@ip-test]# 
[root@ip-test]# echo Testing | echo "${thescript}" | sh
## I get no response

如何解决这个问题?

将脚本作为命令行参数传递。

echo Testing | sh -c "$thescript"

最新更新