2

I write a shell script named as test.sh :

#!/bin/bash
read MY_NAME
echo $MY_NAME

When i execute by file, such as:

./test.sh

everything is ok, but if i execute it by string ,such as:

cat ./test.sh | sh

there is nothing output. Read command did not work when I Execute command using string. How can i fixed it ?

So, if i want execute the script with string and read some value from the stdin, how to work ?

1 Answer 1

3

When you execute the script by a shell running in a pipeline, the stdin of the shell is connected to the pipe, so read reads from the pipe, but there's nothing, as everything has already been read by the shell (or worse, if the script is long enough, read might eat part of it before the shell reads it).

BTW, don't run bash scripts with sh, on many systems, sh and bash aren't identical.

Sign up to request clarification or add additional context in comments.

3 Comments

Even worse, if the script is long enough, sh might not read the entire script, allowing the read command (when executed) to consume a line of the script.
And even if sh and bash are identical, bash will behave differently when invoked as sh.
So, if i want execute the script with string and read some value from the stdin, how to work ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.