How to Store a Linux Command as a Variable in Shell Script

Shell scripting is quite popularly used to automate stuff in Linux. It is used not only for system and server administration purposes but also by regular Linux users for automating day to day stuff on their systems.

A shell script is nothing but a sequence of commands; which a command-line interpreter (Eg. Bash, Zsh) will run. Along with the sequence of commands, there are features like loops, conditional statements, variables that can be used in a shell script.

One such feature is storing an entire command in a variable. Let’s see what we mean by that and how it can be done.

Basically, Linux shells allow you to store any command in a variable, as a string. This is useful for inline complex statements involving multiple commands, redirects, etc. This variable can then be passed to the program ‘eval‘ so that the contents of the variable are executed as a command.

For example, to store the output of command ‘cat test.txt | wc -l‘ in a variable called ‘cnt‘, we can have the following statement in the test.sh script file:

#!/bin/bash

cnt="cat test.txt | wc -l"

Now, to execute this command at any point, we pass the variable as an argument to ‘eval‘, as shown below:

#!/bin/bash

cnt="cat test.txt | wc -l"

eval $cnt

Save and exit the script.

Let’s now run the command and the script itself to verify this.

$ cat test.txt | wc -l
$ chmod + test.sh
$ ./test.sh

Note: Replace test.sh with your script name. Make sure your script file has executed privileges.

Run Command as a Variable in Shell Scripts
Run Command as a Variable in Shell Scripts

As seen in the screenshot above, both results are the same.

Conclusion

In this article, we have seen how to store a Linux command as a variable in the shell script. Although this has been shown in the shell script, you can also do the same on the command line, and then pass the variable to ‘eval‘.

If you have any questions or feedback, let us know in the comments below!

Got something to say? Join the discussion.