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
Creating a Progress Bar in Bash
Publish Date:2025/03/23 Views:94 Category:OPERATING SYSTEM
-
A progress bar is a visual indicator that shows the progress of a task, such as a long-running script or command. It can be used to provide feedback to the user about the status of a task and can also help estimate the time remaining before
Bash variable multiplication
Publish Date:2025/03/23 Views:150 Category:OPERATING SYSTEM
-
This article explains how to multiply two variables in Bash. Multiplying variables in Bash Multiplying two variables is a simple operation in Bash. We can use the arithmetic operator * to multiply two numbers in Bash. In Bash, multiplicatio
Bash md5sum command
Publish Date:2025/03/23 Views:116 Category:OPERATING SYSTEM
-
This article explains how to use the md5sum command in Bash. Bash md5sum command md5sum command prints the 32 character and 128 bit checksum of a given file. This command converts the file into a hash using the MD5 algorithm; the syntax of
Sorting Arrays in Bash
Publish Date:2025/03/23 Views:73 Category:OPERATING SYSTEM
-
Sorting an array is a very common task in any programming language. In Bash scripting, we can also accomplish this task in two different ways. The first one uses any sorting algorithm and the second one uses a built-in keyword in Bash scrip
Multidimensional arrays in Bash
Publish Date:2025/03/23 Views:68 Category:OPERATING SYSTEM
-
Multidimensional array is a very important element for any program. It is mainly used to create table view of data and many other purposes. This article demonstrates how to create a two-dimensional array. In addition, we will discuss the to
Append new data to an array without specifying the index in Bash
Publish Date:2025/03/23 Views:138 Category:OPERATING SYSTEM
-
Arrays are a common part of any programming language. In Bash scripts, you can also use arrays; you can declare, modify, and manipulate arrays. But in this article, we will see step by step how to declare an array and add new data to it. We
String comparison in batch files
Publish Date:2025/03/22 Views:168 Category:OPERATING SYSTEM
-
A string is an ordered collection of characters. You can compare strings using conditional commands in batch files, namely, if, if-else, and for commands. Strings may contain spaces and special characters, which can cause errors in the batc
Remove double quotes from variable in batch file
Publish Date:2025/03/22 Views:177 Category:OPERATING SYSTEM
-
In batch files, variables containing multiple words or spaces must be placed in double quotes, but sometimes, we do not want to see these quotes in the output. These quotes can be removed from the variables in batch files. There are many wa
Reading file into variable in batch script
Publish Date:2025/03/22 Views:121 Category:OPERATING SYSTEM
-
Sometimes, we need to put the entire contents of a file into a variable for various purposes, such as finding specific data from a file, replacing a specific part of a file, etc. In Batch, it is very easy to put the entire file contents in