Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give arguments after Here Document?

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

like image 520
Pan Ruochen Avatar asked Nov 08 '13 08:11

Pan Ruochen


People also ask

How do you end a here document?

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.

How do you add arguments to a script?

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.

What is a here document and explain how its used with a good example?

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.

What is the here document and how can it be used in issuing command and shell scripting?

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.


2 Answers

<<__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']
like image 147
aragaer Avatar answered Oct 15 '22 17:10

aragaer


The arguments are part of the command.

python - arg1 arg2 << ...
like image 28
Ignacio Vazquez-Abrams Avatar answered Oct 15 '22 16:10

Ignacio Vazquez-Abrams