What does ` (backquote/backtick) mean in commands?
This is a backtick. A backtick is not a quotation sign. It has a very special meaning. Everything you type between backticks is evaluated (executed) by the shell before the main command (like chown
in your examples), and the output of that execution is used by that command, just as if you'd type that output at that place in the command line.
So, what
sudo chown `id -u` /somedir
effectively runs (depending on your user ID) is:
sudo chown 1000 /somedir
\ \ \ \
\ \ \ `-- the second argument to "chown" (target directory)
\ \ `-- your user ID, which is the output of "id -u" command
\ `-- "chown" command (change ownership of file/directory)
`-- the "run as root" command; everything after this is run with root privileges
Have a look at this question to learn why, in many situations, it is not a good idea to use backticks.
Btw, if you ever wanted to use a backtick literally, e.g. in a string, you can escape it by placing a backslash (\
) before it.
I would like to add few more points here.
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 `…`
. Both work same, but the $(…)
form is the modern way and has more clarity and readability.
And so
sudo chown $(id -u) /somedir
can be preferred over the other.
And one more thing you need to note here is the command substitution relationship with the bash quoting rules as mentioned in the bash document.
If the substitution appears within double quotes, word splitting and filename expansion are not performed on the results.
One note of clarification rarely covered:
Backticks (sometimes also called Graves because it doubles as a common accent in French and other languages) substitute the Standard Output only, but not the Standard Error.
So to continue the previous example:
file `which hostname`
will work as expected, but in:
file `which hostnameX`
which
will return an error, and that output goes to standard error, rather than substituting onto the command line next to file
; there will be no standard output at all, which you can confirm by running:
which hostnameX
which hostnameX 2>/dev/null
In this case,
file `which hostnameX`
will produce two error messages (the first one, due to which hostnameX
and the second one just after the former, due to file itself, that finds that the file name is missing and so, the whole command
will essentially reduce to just:
file
which, of course, is bad usage, and will return a Usage error.
(if you want to check it by yourself you can try:
file `which hostnameX 2>/dev/null` # just the file-command bad-usage error msg is printed
file `which hostnameX 2>/dev/null` 2>/dev/null # now nothing is printed on the screen :)