Bash – Why can’t I use “$whoami” as a variable in “chown $whoami path”

bashvariable

Why doesn't this work?

[my_user@archlinux ~]$ sudo chown -R ${whoami} /my_folder/path1/path2
chown: missing operand after ‘/my_folder/path1/path2’
Try 'chown --help' for more information.


[my_user@archlinux ~]$ sudo chown -R my_user /my_folder/path1/path2
[my_user@archlinux ~]$ ${whoami}
[my_user@archlinux ~]$ $whoami

But:

[my_user@archlinux ~]$ whoami
my_user

How to use the result of whoami in sudo chown -R?

Best Answer

The variable $whoami does not have a value. You may give it a value with

whoami=$(whoami)

but in this case you may want to use the command substitution $(whoami) directly:

sudo chown -R "$(whoami)" /my_folder/path1/path2

A command substitution, $(...), expands to the output of the command within (minus any trailing newline).

The variable $LOGNAME (and/or $USER) should have the same value as is returned by whoami, which means that you could also do

sudo chown -R "$LOGNAME" /my_folder/path1/path2
Related Question