Home > Mobile >  what we mean by using <<< in shell to execute a python code
what we mean by using <<< in shell to execute a python code

Time:11-28

Hello guys i wanna write a Shell script that runs Python code saved in variable called $code.

So i save the script in variable $code with this command:

$ export CODE='print("Hello world")'

To resolve the problem I write the following script in a file called run:

#!/bin/bash
echo "$CODE" > main.py
python3 main.py

To running the shell script i use:

./run

and its work but I found another answer which I don't understand:

python3 <<< $PYCODE

so what do we mean by using <<<?

CodePudding user response:

In Bash, zsh (and some other shells) <<< is the here string operator. The code you’ve posted is roughly equivalent to

echo -n "$PYCODE" | python3

CodePudding user response:

In bash/unix etc <<< denotes a here string and is a way to pass standard input to commands. <<< is used for strings whereas << denotes a here document, and < is used for passing the contents of a file.

$ python3 <<< 'print("hi there")'
hi there

It passes the word on the right to the standard input of the command on the left.

You could do the same with | but that's only OK if your need for the values is contained, but you still don't have those variables in the current shell of your script, i.e. you don't have other $variables that you want to insert. If you do though, you would use a here-string as in your example, that lets you reference other variables.

Please see: https://en.wikipedia.org/wiki/Here_document

https://linuxhint.com/bash-heredoc-tutorial/

  • Related