Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between eval and backticks (reverse apostrophe)

Tags:

bash

eval

Can anyone tell me what the big difference here is and why the latter doesn't work?

test="ls -l"

Both now work fine:

eval $test
echo `$test`

But in this case:

test="ls -l >> test.log"

eval $test
echo `$test`

The latter will not work. Why is that? I know that eval is just executing a script while the apostrophes are executing it and return the result as a string. What makes it not possible to use >> or simmilar stuff inside the command to execute? Maybe is there a way to make it work with apostrophes and I'm doing something wrong?

like image 730
Kelu Thatsall Avatar asked Sep 17 '13 12:09

Kelu Thatsall


People also ask

What does `` mean in Linux?

The backtick `…` is actually called command substitution. The purpose of command substitution is to evaluate the command which is placed inside the backtick and provide its result as an argument to the actual command. The command substitution can be done in two ways one is using $(…) and the other is `…` .

What does backtick mean in shell?

The backtick allows you to assign the output of a shell command to a variable. While this doesn't seem like much, it is a major building block in script programming. You must surround the entire command line command with backtick characters: # testing=`date`

Why we use Backticks in Linux?

In my Perl scripts, I would use the backtick operator to run a command in the operating system and return the output to continue the logic in the script. The backtick operator is also available in shell scripts, and because it is so easy to combine with other commands, I started using it a lot.


1 Answers

When you're using backticks to execute your command, the command being sent to the shell is:

ls -l '>>' test.log

which makes both >> and test.log arguments to ls (note the quotes around >>).

While using eval, the command being executed is:

ls -l >> test.log

(Execute your script by saying bash -vx scriptname to see what's happening.)

like image 136
devnull Avatar answered Oct 06 '22 19:10

devnull