20

Suppose I have a script: my_script.sh

Instead of doing

./my_script.sh

I want to do something like:

cat my_script.sh | <some command here>

such that the script executes. Is this possible?

The use case is if the script I want to execute is the output of a wget or s3cat, etc. Right now I save it to a temporary file, change it to executable, and then run it. Is there a way to do it directly?

1
  • 3
    You have to be very careful doing this. If anything inside of your script reads from stdin (for example, any command that prompts the user for "Yes/No"), it will consume lines from your script, and those lines will not get executed. Commented Oct 20, 2014 at 19:26

3 Answers 3

26

Just pipe it to your favorite shell, for example:

$ cat my_script.sh
set -x
echo hello
$ cat my_script.sh | sh
+ echo hello
hello

(The set -x makes the shell print out each statement it is about to run before it runs it, handy for debugging, but it has nothing to do with your issue specifically - just there for demo purposes.)

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

3 Comments

if the script specifies the shell type with the "#!" stuff, then does that override whatever shell I pipe it into?
No, that won't work, the shell you pipe to will interpret that as a comment (i.e. not at all). That's going to be tricky to do without a temp file. (Oh, and you do realize that this (wget'ing stuff and running it) is potentially really dangerous, right?)
Okay, thanks. And yes, agreed that it's dangerous if the file is not from a trusted source (though it's just as dangerous as automatically saving it to a file and then executing it).
6

You could use stdin from pipe:

cat my_script.sh | xargs -i <some_command> {}

or:

cat my_script.sh | bash -

or (just from stdin):

bash < my_script.sh

Comments

0

RVM recommends this method to run their installer:

bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)

Comments

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.