There is a way to embed other language scripts or code in Bash Script. In this article, you will learn about it.
Embedding other language code in Bash shell script
We may need to include other language scripts in Bash for certain reasons such as the fact that a certain complex task is already coded in another language. For example, storing the values for pi
; other languages could be better at getting the precise value of pi due to their library functions. Let us assume that the user knows Lua language scripting. Then, embedding Lua language script in Bash would be undertaken as follows:
$ export PI=$(lua -e "print(string.format('%f', math.pi))")
The preceding line will inform Bash to save the output of Lua code in variablePI
. In this example, the-e
option to Lua informs Lua interpreter to execute next code. The Lua code will be enclosed in quotes.
The procedure to embed other language code is to call that language command itself, followed by the-c
or-e
options. We will study the-c
and-e
options later on in this section.
In certain cases, such as Python, we may need to type version of python as well, for example, Python (for Python 2.x version) or Python 3 (for Python 3.x version).
Please ensure that the embedding of other languages code should only be done if it is really necessary. Bash cannot do the certain tasks efficiently, but other languages can do it better way such as complex mathematical calculations and plotting of graphs using python. Every language has certain good points as well as limitations.
The syntax to embed other language code is similar for all languages. The parameter passed will only differentiate between-c
or-e
, depending on a particular language. At the end of this chapter, a summary is given. You may refer to the table for finding an option for embedding language of your choice.
While embedding other languages, we must take care about escape characters, which will be read by Bash scripts. The following example is to be avoided:
perl -e 'print "Hello I am Perl Script.n" '
In the preceding code line,.n
will be interpreted differently by Bash than expected. We should make it as.n
. Then, Bash will interpret it correctly as we have escapedn
properly.
The updated code will be seen as follows:
perl -e "print "Hello I am PerlScript.n""
While embedding other language code, we should take care of quotes, backslashes, dollar signs, and a few other characters.
Sending output to Bash Script
There are many ways to send or receive datafromembedded code. Other language-embedded code can send data to Bash using piping, saving, writing, or printing. Other language-embedded code can receive data through variables, files, user input, or pipes.
The following is an example of other language code sending output to Bash using pipe:
ksh -c "ls" | cat > ./save_to_file
In the preceding command,ksh
is sending directory content to bash by pipe, which will be stored in the file.
We can eliminate the use of pipe from the preceding example as follows:
ksh -c "ls" > ./save_to_file
As we have eliminated the use of pipe, the preceding command has become more efficient. It is better to eliminate the middleman if possible.
Storing other language output to Bash variable
To save the output of other language code in Bash, the example is as follows:
$ result=$(python3 -c "print(10+15)")
In the preceding example code, we have embeddedpython3
code in bash shell. The output of the print command which addition of two numbers will be stored in abash
variable result.
If we want to print the output of embedded language code directly on screen, then the example code is as follows:
$ python3 -c "print(Hello World)"
Sending data to an embedded language code
If we want to send data to the embedded language script, then one way is to send it via variable content. Look at the following example:
$ export location="/etc"; ksh -c "ls $location"
In the preceding example, we are initializing a variable location with the path or folder name. When shell executes the ksh
command, it will pass path as content of $location
. Then, ksh
will print the content of the directory required.
Using data from file by embedded language
If we want the embedded language to open a file and use its contents for further processing, then follow this example. We have used the python3
way of opening and reading the contents of a file:
$ python3 -c "import sys, io; DATA = open('/home/student/sample.txt', 'r').read()" | sed -e "s|Hello|Bye|g" | less
In the preceding command-line code, the python3
command is opening and reading contents of a file. Then, it sends the content to the file to bash
shell command sed
by pipe. Sed replaces text Hello
from file to Bye
, and finally, it is displayed on screen by the less command.
Sending user input to the embedded code
If we want to send user-entered keyboard data directly to embedded code, then we should use the embedded language input-related command:
$ ksh -c "read INPUT; echo "You_typed_'$INPUT'""
This would allow the code to accept input from users. It waits for a user to type and hit Enter. After pressing Enter, this line would prints You_typed_Hello there
Embedding Python code in Bash shell Script
Nowadays, Python is apopularscripting language, especially in data science and automation. You can integrate Python code very easily in bash scripts. We have used here doc for this purpose.
Let’s write the shell scriptembed_01.sh
as follows:
embed_01.sh
#!/bin/bash
function now_date_time
{
python - <<START
import datetime
value = datetime.datetime.now()
print (value)
START
}
now_date_time
Date_Time=$(now_date_time)
echo "Date and time now = $Date_Time"
Let’s test the program as follows:
$ chmod +x embed_01.sh
$ ./ embed_01.sh
The output is as follows:
Output:
2018-04-27 01:53:58.719905Date and time now = 2018-04-27 01:53:58.770123
Let’s see an example of using bash variables in embedded Python code.
Let’s write the shell scriptembed_02.sh
as follows:
embed_02.sh
#!/bin/bash
export price=100
python - <<END
import os
print "price:", os.environ['price']
END
cost=200 python - <<END
import os
print "cost:", os.environ['cost']
END
Let’s test the program as follows:
$ chmod +x embed_02.sh
$ ./ embed_02.sh
The output is as follows:
Output:
price: 100
cost: 200
Embedding Ruby code
You can run Ruby code from a bash shell script. Inthiscase, you will have one bash script and a Ruby script. You can simply call the Ruby script from within the Bash shell script.
If you want tocombine both scripts in one script, then we will need to use the << heredoc
functionality of Bash shell.
Let’s write the embed_03.sh
script:
embed_03.sh
#!/usr/bin/env sh
echo "This is bashScript!"
/usr/bin/env rubyScript <<-EndOfRuby
puts 'This is ruby!'
EndOfRuby
Let’s test the program:
$ chmod +x embed_03.sh
$ ./ embed_03.sh
The output is as follows:
Output:
This is bashScript!
This is rubyScript!
Embedding other language code in Bash – comparative study
Most of languages allow othercodefrom languages in their code. However, there are certain advantages as well as disadvantages.
The advantages are as follows:
- More functionality and variety
- Efficient code (if properly used)
- Useful for programmers because they can implement or reuse algorithms or functionality from a different language. Different languages have
diff
strong points.
The disadvantages are as follows:
- Execution is slow (if implementation improperly)
- Programmers need to know many languages
- Different language tools need to be installed
- Code becomes fragmented, sometimes difficult to understand
A summary of commands for embedding other programming languages
A summary of the commands used for embedding various other programming languages is as follows:
Programming language
Command for embedding script or code
ash
ash -c ""
ruby
ruby -e ""
jruby
jruby -e ""
rubyjs
rubyjs -e ""
python
python -c ""
python3
python3 -c ""
jython
jython -c ""
cython
cython -c ""
perl
perl -e ""
csh
csh -c ""
tcsh
tcsh -c ""
mksh
mksh -c ""
ksh
ksh -c ""
zsh
zsh -c ""
dash
dash -c ""
coffee
coffee -e ""
lua
lua -e ""
scilab
scilab -e ""