I want to execute a python script via “Here Document” following some arguments in my bash shell script, as follows
python <<'__SCRIPT__'
...
__SCRIPT__
ARG1 ARG2 ...
But don't know how to give these arguments. I have tried putting them following python, following SCRIPT and a new line right after SCRIPT. But errors are reported in all of the cases when executed.
So what is the right way?
BR, RUOCHEN
To use here-document in any bash script, you have to use the symbol << followed by any delimiting identifier after any bash command and close the HereDoc by using the same delimiting identifier at the end of the text.
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.
Here document (Heredoc) is an input or file stream literal that is treated as a special block of code. This block of code will be passed to a command for processing. Heredoc originates in UNIX shells and can be found in popular Linux shells like sh, tcsh, ksh, bash, zsh, csh.
A here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command, such as ftp, cat, or the ex text editor. Choose a limit string sufficiently unusual that it will not occur anywhere in the command list and confuse matters.
<<__SCRIPT__
is not actually a script passed to python, it's a stream containing the script. You have to tell python where to get the script, which is -
in this case. That's why python - arg1 arg2 <<'__SCRIPT__'
:
$ cat here-py.sh
python - foo bar <<__SCRIPT__
import sys
print(sys.argv)
__SCRIPT__
$ ./here-py.sh
['-', 'foo', 'bar']
The arguments are part of the command.
python - arg1 arg2 << ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With