Using eval
Command
Use the eval
command to run a string as a command in Bash
1 2 3 |
eval "echo Hello, world!" |
1 2 3 |
Hello, world! |
In the above code, the eval
command evaluates and executes the arguments passed to it as a Bash command. The argument passed to eval
is an echo Hello, world!
string. This string represents the command that we want to execute dynamically. Therefore, the echo Hello, world!
string argument is evaluated by the eval
command when executed as a Bash command.
In the above case, the argument passed to echo
was Hello, world!
printed to the terminal window, also referred to as the standard output. Let’s take another example below.
1 2 3 4 |
dir="/home/user/Documents" eval "ls -l $dir" |
1 2 3 4 5 |
-rw-r--r-- 1 user user 4096 Mar 14 10:00 example.txt drwxr-xr-x 2 user user 4096 Mar 14 09:00 example_folder -rw-r--r-- 1 user user 2048 Mar 13 18:00 another_file.txt |
In the above code, The dir="/home/user/Documents"
defines a variable dir
and assigns it the value /home/user/Documents
. The ls
command is a built-in command in bash that lists a directory’s contents. The -l
option produces a long listing format that displays detailed information about each file in the directory.
Theeval
evaluates the string ls -l /home/user/Documents
as a Bash command and executes it. The output of the ls
command is printed to the standard output, which in this case is the terminal window, showing a long listing of the files in the Documents
directory.
Until now, we used the eval
with commands enclosed within the double quotes. Can we store the command in a variable and use that variable with eval
? Let’s see it below.
1 2 3 4 |
command="rm -rf /" eval $command |
1 2 3 4 |
rm: it is dangerous to operate recursively on '/' rm: use --no-preserve-root to override this failsafe |
In the above code, the eval
command evaluates the string rm -rf /
as a bash command after substituting the value of the variable command. Unfortunately, the string rm -rf /
is a very dangerous command instructing the system to delete everything in the root
directory & all its subdirectories /
recursively without confirmation.
It will result in the deletion of all system files and directories. In this case, the output will be a warning message indicating that the rm
command is currently attempting to unmount the entire file system and that the failure should be overridden with the --no-preserve-root
. This example shows the importance of escaping variables in command strings to prevent unintended consequences.
Considering the above solutions, running a string as a command in Bash can be a powerful tool for automating tasks and simplifying complex workflows. However, it carries a significant security risk if not used carefully. Therefore, to use this feature safely, it is essential to properly validate and sanitize any user input used in the command string.
That’s all about run String as command in Bash.