10

Imagine you have a silly script test.sh to which arguments are passed that would look like this:

bash test.sh arg1 arg2 arg3

with test.sh being a silly script that displays its command line:

#!/bin/bash
echo "$0 $*"

I would like to do the same using bash heredoc << to feed the script to bash. So I tried this :

bash <<'EOF' -- arg1 arg2 arg3
echo "$0 $*"
EOF

But it fails with error

bash: arg1: No such file or directory

Any idea ?

2 Answers 2

13

The here document is passed to the inner bash on its standard input. You need to instruct bash to read from standard input. With no command line arguments, this happens automatically. If there's at least one non-option argument and no -s or -c option, the first non-option argument is the name of the script file to run. You can pass the -s option to tell bash to read from standard input.

bash <<'EOF' -s -- arg1 arg2 arg3
echo "$0 $*"
EOF
1

Alternatively, on most systems, you can do:

bash /dev/fd/3 3<< 'EOF' arg1 arg2 arg3
echo "$0 $*"
IFS= read -rp "Enter something: "
printf 'You entered: "%s"\n' "$REPLY"
EOF

That way, your here-script can still access stdin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.