Execute commands in a variable in a Bash script
This article is about storing Bash commands in a variable and then executing it directly from that variable. First, we will discuss the various ways to execute commands contained in a variable, followed by several script examples.
Let’s get started.
Bash script variables
Variables are a fundamental feature supported by Bash. Whether you use them in if control structures, case structures, or in scripts, they not only organize your scripts but also make them easier to understand.
You can also run them as scripts, which makes life especially easy when you have many commands piped through and the commands are long. This will reduce the length of your script, which might be a hundred words long to one, maybe not even a dozen words long.
Imagine debugging a script that's a hundred words long versus one that's less than a dozen words long; think about the time you could save.
Sometimes, we need to write Bash wrappers that take commands from the user, store them into variables, and conditionally run some of these commands after applying some business logic (maybe a series of if-else decisions). Now, in these scenarios, we need to look at methods that can help us parse and interpret the commands stored in variables to run them as Bash commands.
Here we will discuss some of the most efficient ways to run commands contained in variables.
Use Eval command in Bash script to execute commands in variables
Some Bash scripts require you to build a string using input values or variables (for example) and run it as a command at the end. The eval command is the answer in these cases.
To evaluate arguments like a shell command, use the Bash eval command.
The shell command receives a string of parameters and uses that string to execute a command. The command is then executed in the current shell via eval.
This command is useful when executing commands that use specific operators or reserved items.
grammar:
eval [arguments...]
Arguments are passed to this command, combined into a string literal, and then sent to Bash for execution. This command returns the exit status after executing the command.
If no arguments are passed to this command or null is passed, it returns 0 as the exit status.
Example 1 : Count the number of words in a file.
Suppose we have a file mysample.txt which contains several lines of text. If we have to count the number of words in that file, we can use the wc -w command.
We will use the eval command to perform this task. The Bash script will be:
#!/bin/bash
wordcount="wc -w mysample.txt"
eval $wordcount
Let's see its output:
Example 2 : Building a command using multiple variables.
Suppose we need to print a statement Welcome to Eval Command. We can use the eval command to do this:
#!/bin/bash
var1="Welcome to Eval Command"
comm1="echo"
eval $comm2 $var1
In this script, we create two variables, one containing the message to be printed and the other containing the echo command. We pass these two variables to the eval command and it builds the entire command accordingly.
After executing this script, we will get the following output:
Example 3 : Print the value of a variable.
In the following example, we will print the value of a variable containing another variable.
#!/bin/bash
str1="my script"
str2= str1
comm="echo "
eval $comm '$str2'
The output of the above script will be:
Example 4 : Print the sum of numbers.
In the following example, we will use a for loop in a script to print the sum of numbers in the range of 1 to 4. We will then use the eval command to print the sum.
The script for this question is:
#!/bin/bash
sum=0
for n in {1..4}
do
sum=$(($sum+$n))
done
comm="echo 'The result of sum from 1-4 is: '"
eval $comm $sum
The output of the above script will be:
Execute commands in variables in Bash scripts using bash with the -c flag
By default, the bash command interpreter reads commands from standard input or from a file and executes them. However, if the -c flag is set, the bash interpreter reads commands from the first string argument (which should be a non-option argument).
Therefore, we can use it to execute commands stored in Bash string variables.
For example, the following script first assigns the ls command string to the COMMAND variable. It then uses the bash interpreter with the -c command to use the COMMAND variable as input.
#!/bin/bash
COMMAND="ls"
bash -c $COMMAND
The above command will list all the directories and files under the current working directory of the script file.
Use command substitution $() in Bash scripts to execute commands in variables
We can use command substitution to run a command stored in a variable:
#!/bin/bash
COMMAND="ls"
$(echo $COMMAND)
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to decompress x.tar.xz format files under Linux
Publish Date:2025/04/08 Views:186 Category:OPERATING SYSTEM
-
A lot of software found today is in the tar.xz format, which is a lossless data compression file format that uses the LZMA compression algorithm. Like gzip and bzip2, it supports multiple file compression, but the convention is not to compr
Summary of vim common commands
Publish Date:2025/04/08 Views:115 Category:OPERATING SYSTEM
-
In Linux, the best editor should be vim. However, the complex commands behind vim's powerful functions also make us daunted. Of course, these commands do not need to be memorized by rote. As long as you practice using vim more, you can reme
Detailed explanation of command return value $? in Linux
Publish Date:2025/04/08 Views:58 Category:OPERATING SYSTEM
-
? is a special variable. This variable represents the return value of the previous command. That is to say, when we run certain commands, these commands will return a code after running. Generally, if the command is successfully run, the re
Common judgment formulas for Linux script shell
Publish Date:2025/04/08 Views:159 Category:OPERATING SYSTEM
-
In shell script programming, predicates are often used. There are two ways to use predicates, one is to use test, and the other is to use []. Let's take a look at how to use these two methods through two simple examples. Example 1 # test –
Shell script programming practice - specify a directory to delete files
Publish Date:2025/04/08 Views:98 Category:OPERATING SYSTEM
-
Usually, in Linux system we need to frequently delete some temporary files or junk files. If we delete them one by one manually, it will be quite troublesome. I have also been learning shell script programming recently, so I tried to write
Use of Linux command at - set time to execute command only once
Publish Date:2025/04/08 Views:158 Category:OPERATING SYSTEM
-
This article mainly involves a knowledge point, which is the atd service. Similar to this service is the crond service. The functions of these two services can be similar to the two functional functions of javascript. Those who have learned
Use of Linux command crontab - loop execution of set commands
Publish Date:2025/04/08 Views:170 Category:OPERATING SYSTEM
-
Compared with at , which executes a command only once, crontab, which we are going to talk about in this article, executes the set commands in a loop. Similarly, the use of crontab requires the support of the crond service. The service is s
Linux practice - regularly delete files under the directory
Publish Date:2025/04/08 Views:198 Category:OPERATING SYSTEM
-
Since we want to delete the files under the directory regularly, we need to use the Linux crontab command. And the content format of each work routine is also introduced in the format of each crontab work. Similarly, we need to use shell sc
How to use the Linux file remote copy command scp
Publish Date:2025/04/08 Views:151 Category:OPERATING SYSTEM
-
Scp copies files between two hosts over the network, and the data is encrypted during transmission. Its underlying layer uses ssh for data transmission. And it has the same authentication mechanism and the same security level as ssh. When u