-1

What is the difference of using or not using the BACK QUOTE `

For example, both the code works regardless.

First example with the BACK QUOTE, second example without BACK QUOTE.

Thank you so much in advance for your help.

if [ "`/usr/bin/whoami`" != "root" ] ; then
/bin/echo "This script must be run as root or sudo."
exit 0
fi

if [ "/usr/bin/whoami" != "root" ] ; then
/bin/echo "This script must be run as root or sudo."
exit 0
fi
Fabio
  • 237
  • 2
  • 13
  • Did you run the script as root and get expected results? I'm thinking the second would not give the correct result in that case. You are just comparing two different strings. – lurker Jan 30 '20 at 15:20
  • 3
    The first actually runs the command `whoami`. You *should* use `"$(/usr/bin/whoami)"`, though, instead of backquotes. – chepner Jan 30 '20 at 15:29
  • 3
    You could just compare the output of ``echo "`/usr/bin/whoami`"`` and `echo "/usr/bin/whoami"`; the difference would be obvious. – chepner Jan 30 '20 at 15:31

1 Answers1

2

In first case you compare in if the result of execution of command /usr/bin/whoami (this is what backticks do)

In second case you compare two strings

/usr/bin/whoami

and

root

one more example can be:

if [ "`date`" = "date" ]
then echo this is true
fi

the above code will NOT work because you compare string "Thu Jan 30 17:03:54 CET 2020" and string "date"

if [ "date" = "date" ]
then echo this is true
fi

the above code will work :)

Romeo Ninov
  • 6,538
  • 1
  • 22
  • 31
  • 1
    Thanks Can you please give me another simple example of : In first case you compare in if the result of execution of command /usr/bin/whoami (this is what backticks do) – Fabio Jan 30 '20 at 15:28