Search code examples
shellshstdin

retaining stdin if script is run through pipe


I have the following script which is built to read in stdin and print it out:

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

This script works if run the "normal"/"expected" way:

echo Testing | ./myscript.sh 
Testing

However, I need to run it differently...i.e. storing the script in a variable and running it. But the problem is, when I do, i lose the stdin information.

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

How can I resolve this?


Solution

  • Pass the script as a command line argument instead.

    echo Testing | sh -c "$thescript"