store command in variable in shell script

How to Store Command in Variable in Shell Script

Linux allows you to automate tasks using shell commands and scripts. Typically we store number or strings in shell variables & scripts. But sometimes you may need to store a specific command in shell variable. In this article, we will learn how to store command in variable in shell script.


How to Store Command in Variable in Shell Script

Here is the typical syntax to store value in variable in shell.

var_name=value

Once the value is stored in variable, you can refer to it by adding $ prefix to the variable.

$var_name

Let us say you want to store the following command in shell variable.

ls | wc

If you want to store the above command into a shell variable x, you need to do it as shown below.

x="ls | wc"

Please note, you need to enclose the command within quotes, as a string. You need to assign this string in shell variable.

If you want to execute such a command stored in variable, you can do it using eval command.

eval "$x"
     14      14     164

On some systems, you can run the above eval function, even without enclosing your shell variable $x within quotes.

eval $x

If you want to assign the value of x to another variable y, you can easily do it just like you would assign any shell variable to another.

y=x

Now if you run eval command on new variable, you will see the same output.

eval $y
     14      14     164

But please note, use eval function only if there are no shell variables in your command, or you absolutely trust the command, otherwise you will allow others to inject variables into your script. For example, if you save the following command in your shell script then malicious users and programs can change the value of shell variable $x by simply changing the value of $name.

x="ls '$name' | wc"

In this short article, we have learnt how to save command in variable in shell script. You can customize it as per your requirement.

Also read:

Tar Directory Excludes Files & Directories
How to Change Color Schemes in Vim
Python Script to Check URL Status
How to Create Executable in Python
How to Store JSON Data in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *