Unix - eval command example

Unix - eval command example

Have you ever have the need to remotely execute a long list of command to a list of unix machines to perform tasks like gathering their information? Well, if you did then you will mostly came across an issue where you ran out of quoting variables to quote the long list of command that you need to execute.

For example using "" (double quote) to execute a command uptime remotely.
root@myserver # ssh root@server1 "uptime"

If you need to execute uptime along with for example df and search for string "nfs" using awk you can use the below command.
root@myserver # ssh root@server1 "uptime;df |awk '/nfs/'"

So far the above two example are simple and doable without much issue as we have used double quote (") and single quote (') to wrap our command. What if you need to execute more command and ran of out quotes? Well one easy solution is to ssh multiple times to same machine to execute different sets of command. To some that might look troublesome and inefficient. Another more efficient way is to use eval command.

Eval Command. Eval is a built in linux or unix command. The eval command is used to execute the arguments as a shell command on unix or linux system.

How to use it? First save the commands that you need to execute in a file. You can use vi editor. Below is the content of the file which contains the needed commands to be executed on a unix machine.
root@myserver # cat commands.txt
hostname;uptime;sar -u 3 3;df |awk '/nfs/';echo "hostname"

Next create a simple script to do what we need where in this case is to ssh remotely to a unix machine to executed the needed command contains in file commands.txt. Below is what the content of the script would look like.
root@myserver # cat script.sh
commands=`cat commands.txt` ssh root@server1 eval $commands

Remember to set the script to executable with chmod and it is ready to be used.
0 (0)
Article Rating (No Votes)
Rate this article
There are no attachments for this article.
There are no comments for this article. Be the first to post a comment.
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
Convert CSV to JSON with bash script
Viewed 4893 times since Mon, Jan 20, 2020
Epoch & Unix Timestamp Conversion Tools
Viewed 46576 times since Fri, Jun 22, 2018
Transform XML to CSV Format | Unix String Pattern Manipulation The Ugly Way
Viewed 4748 times since Sun, Jan 9, 2022
Convert JSON to CSV with bash script
Viewed 11991 times since Mon, Jan 20, 2020
java Simple Java JDBC Program To Execute SQL Update Statement
Viewed 11768 times since Sun, Jan 9, 2022
bash for do done AIX
Viewed 1605 times since Mon, Jun 4, 2018
Unix - Find command examples
Viewed 4321 times since Fri, Jun 8, 2018
Display basic information about Physical Volumes
Viewed 3122 times since Sun, Jun 3, 2018
Unix - Examples for grep command
Viewed 2781 times since Fri, Jun 8, 2018
Convert CSV to JSON with jq
Viewed 26736 times since Mon, Jan 20, 2020