Piping a script with "read" to bash
Solution 1
read
reads from standard input. But the standard input of the bash process is already taken by the script. Depending on the shell, either read
won't read anything because the shell has already read and parsed the whole script, or read
will consume unpredictable lines in the script.
Simple solution:
bash -c "$(wget -O - http://example.com/my-script.sh)"
More complex solution, more for education purposes than to illustrate a good solution for this particular scenario:
echo '{ exec </dev/tty; wget -O - http://example.com/my-script.sh; }' | bash
Solution 2
Process substitution will do what you want:
bash <(wget ...)
That said, I have to question your motivation here. If you control the webserver (and use https) then maybe this might make sense. But just running a script from the internet blind is very risky.
Solution 3
Is there something wrong with :
wget -O tmpscript.sh http://example.com/my-script.sh
chmod +x tmpscript.sh
tmpscript.sh
?
Related videos on Youtube
Robin Winslow
I'm a web developer at Canonical. I have a blog about web dev, politics and other things. I'm interested in UX, client- and server-side development, code architecture and microformats. I'm not a fan of intellectual property, and I love freedom of information and open-source.
Updated on September 18, 2022Comments
-
Robin Winslow over 1 year
I need to run a script by piping it through
bash
withwget
(rather than running it directly with bash).$ wget -O - http://example.com/my-script.sh | bash
It's not working because my script has
read
statements in it. For some reason these don't work when piping to bash:# Piping to bash works in general $ echo 'hi' hi $ echo "echo 'hi'" | bash hi # `read` works directly $ read -p "input: " var input: <prompt> # But not when piping - returns immediately $ echo 'read -p "input: " var' | bash $
Instead of prompting
input:
and asking for a value as it should, the read command just gets passed over bybash
.Does anyone know how I can pipe a script with
read
tobash
? -
Robin Winslow over 9 yearsAwesome thanks. This is almost as elegant.
-
Robin Winslow over 9 years'cos then I have to create a file. I mean it'd work, it's just a bit messy.
-
Govind over 9 yearsTrue. Though that's a good reason to use
/tmp
, lots of programs use temp files. I'd be leary of running any downloaded scripts immediately without taking a look first... -
Govind over 9 yearsI'm thinking of anyone else finding this question (a totally new user perhaps) might not know any better.
-
Robin Winslow over 9 years
just running a script from the internet blind is very risky
- aye we know it's risky, but people can choose to trust scripts from certain organisations. See the discussion in comments on @Xen2050's answer.