The shell will read the script to execute from standard input if you start the shell with its -s
option. This will stop it from believing the first option is the name of the script file.
So use bash -s "$1" test1 test2
.
Note that if the script (or any utility called from within the script) is reading from the standard input stream, it will consume the script itself. This is therefore not suitable for scripts that need the standard input stream for something. Note also that I used bash
and not sh
. This is necessary to create functions with the non-standard function
keyword.
Assuming the function (which I will rename into mytest
as test
is the name of a built-in command) should output the 2nd and 3rd command line arguments of the script, these need to be passed to the function when you call it.
You may do this by passing all the arguments to the function using
mytest "$@"
... or, you could just pass the two that you need (and change the function to output "$1"
and "$2"
instead, which would be its two first arguments):
mytest "$2" "$3"
You also need to quote all expansions, for example, the $1
on the command line, as well as $2
and $3
in the script itself. See When is double-quoting necessary?
The script needs to be passed to the shell using a quoted here-document or the expansions in the script would be carried out by the invoking shell rather than by the bash
shell you are starting. You quote a here-document by quoting any part of the initial here-document delimiter.
Taking all these things into consideration, you may want to use the following:
bash -s "$1" test1 test2 <<'END_SCRIPT'
function mytest {
echo "$2"
echo "$3"
}
mytest "$@"
END_SCRIPT
Or, with sh
:
sh -s "$1" test1 test2 <<'END_SCRIPT'
mytest () {
echo "$2"
echo "$3"
}
mytest "$@"
END_SCRIPT