Tristan Tristan - 6 months ago 15
Linux Question

Execute bash script from URL

Say I have a file at the URL "http://mywebsite.com/myscript.txt" that contains a script:

#!/bin/bash
echo "Hello, world!"
read -p "What is your name? " name
echo "Hello, ${name}!"


And I'd like to run this script without first saving it to a file. How do I do this?

Now, I've seen the syntax:

bash < <(curl -s http://mywebsite.com/myscript.txt)


But this doesn't seem to work like it would if I saved to a file and then executed. For example readline doesn't work, and the output is just:

$ bash < <(curl -s http://mywebsite.com/myscript.txt)
Hello, world!


Similarly, I've tried:

curl -s http://mywebsite.com/myscript.txt | bash -s --


With the same results.

Originally I had a solution like:

timestamp=`date +%Y%m%d%H%M%S`
curl -s http://mywebsite.com/myscript.txt -o /tmp/.myscript.${timestamp}.tmp
bash /tmp/.myscript.${timestamp}.tmp
rm -f /tmp/.myscript.${timestamp}.tmp


But this seems sloppy, and I'd like a more elegant solution.

I'm aware of the security issues regarding running a shell script from a URL, but let's ignore all of that for right now.

Answer
source <(curl -s http://mywebsite.com/myscript.txt)

ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; bash takes a filename to execute just fine without redirection, and <(command) syntax provides a path.

bash <(curl -s http://mywebsite.com/myscript.txt)

It may be clearer if you look at the output of echo <(cat /dev/null)