Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run script commands from stdin, with arguments

Tags:

shell

ssh

I have a collection of small helper scripts for a more complex shell script, and while this works well, I decided I wanted to reduce this into a single script for a variety of reasons.

So I'm thinking I'll use here documents so that I can create "nested" shell scripts for running either locally or remotely as appropriate. This works well enough as I can do the follow:

#!/bin/sh
nested_script=$(cat << 'NESTED_SCRIPT'
    # Script commands
NESTED_SCRIPT
)
echo "$nested_script" | sh

Not the most functional example, but the fact that I can send it to ssh instead makes this very useful.

However, the problem I'm having is that I can't figure out how to also supply arguments to the nested script, as if I add anything to the sh command then it interprets it as a file to run and ignores standard input entirely.

On my local machine I can do echo "$script" | sh /dev/stdin "foo" "bar" and it will work perfectly, but I don't believe the remote machines I'm working with support the use of /dev/stdin in that way.

Are there any other solutions? Currently I'm forcing the arguments into the script string using sed but that isn't a very nice way to do it.

For those wondering; the reason I'm trying to do this this way is that my nested scripts may be running locally, or may be running remotely, depending upon whether a host is supplied. I don't really want to create files on the remote host to run but would rather just run the commands remotely, which this method seems like it would enable (if I could get it to work like I want).

like image 829
Haravikk Avatar asked Mar 24 '23 06:03

Haravikk


1 Answers

Use sh -s:

echo "$nested_script" | sh -s "foo" "bar"

You could also have passed the script as a parameter with -c:

sh -c "$nested_script" -- "foo" "bar"

This frees up the script's stdin.

like image 92
that other guy Avatar answered Apr 01 '23 19:04

that other guy