如果脚本是 运行 通过管道保留标准输入

retaining stdin if script is run through pipe

我有以下脚本,用于读取标准输入并将其打印出来:

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

如果 运行 "normal"/"expected" 方式,此脚本有效:

echo Testing | ./myscript.sh 
Testing

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

[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"