0

I do not understand why the output is the username because in line 3 and 4 must print /usr/bin/whoami. please explantation simple to me

#!/bin/bash

WHEREWHOAMI="`which whoami`"
ROOTORNOT="`$WHEREWHOAMI`"
echo "$ROOTORNOT"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 3
    Run the script with `set -x` to see what the commands expand to. – Benjamin W. Mar 19 '19 at 19:56
  • 1
    I often find [explainshell](https://explainshell.com/explain?cmd=WHEREWHOAMI%3D%22%60which+whoami%60%22+ROOTORNOT%3D%22%60%24WHEREWHOAMI%60%22+echo+%22%24ROOTORNOT%22) to be of use in these scenarios. – treedust Mar 19 '19 at 20:25
  • Possible duplicate of [What is the difference between $(command) and \`command\` in shell programming?](https://stackoverflow.com/q/4708549/608639) and [Command substitution: backticks or dollar sign / paren enclosed?](https://stackoverflow.com/q/9405478/608639) – jww Mar 20 '19 at 01:01
  • Related to using `which`, you usually want to use `command -v`. Also see [How to check if a program exists from a Bash script?](https://stackoverflow.com/q/592620/608639) and [How to check if command exists in a shell script?](https://stackoverflow.com/q/7522712/608639) – jww Mar 20 '19 at 01:02

2 Answers2

1

The variable ROOTORNOT is set to the output of the execution of WHEREWHOAMI which in turn is the output of the command which whoami.

WHEREWHOAMI=`which whoami`  # <- /usr/bin/whoami
ROOTWHOAMI="`$WHEREWHOAMI`" # <- `/usr/bin/whoami`  # <- username

You can easily figure out what is going on if you add the set -x flag to your script. Example:

$ set -x
$ WHEREWHOAMI="`which whoami`"
++ alias
++ declare -f
++ /usr/bin/which --tty-only --read-alias --read-functions --show-tilde --show-dot whoami
+ WHEREWHOAMI=/usr/bin/whoami
$ ROOTORNOT="`$WHEREWHOAMI`"
++ /usr/bin/whoami
+ ROOTORNOT=kvantour
$ echo "$ROOTORNOT"
+ echo kvantour
kvantour
$ 
kvantour
  • 25,269
  • 4
  • 47
  • 72
1

Backticks are evaluated even inside double quotes.
(Suggestion - don't use backticks. use $() instead.)

WHEREWHOAMI="`which whoami`"

This executes which whoami and assigns /usr/bin/whoami to WHEREWHOAMI.

ROOTORNOT="`$WHEREWHOAMI`"

This executes /usr/bin/whoami in backticks, and assigns the USERNAME result to ROOTORNOT.

It's doing exactly what it should.
Is that not what you indended?

Perhaps what you wanted was something like -

$: [[ $( $(which whoami) ) == root ]] && echo ROOT || echo not-root
not-root

Though I do suggest storing the value and comparing that. Is there a reason you can't just use

if [[ root == "$LOGNAME" ]] 
then : ...

?

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36