What does ` (backquote/backtick) mean in commands?

  • I came across the following command:

    sudo chown `id -u` /somedir

    and I wonder: what is the meaning of the ` symbol. I noticed for instance that while the command above works well, the one below does not:

    sudo chown 'id -u' /somedir
  • 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.

    This explains backticks pretty well, but using `$(your expression)`is a better way to do the same thing as `$()` allows you to nest expressions. for instance: `cd $(dirname $(type -P touch))` will cd you into the directory containing the `touch` command

    @KhajaMinhajuddin You're definitely right about nesting - the above mentioned question covers it in detail. But even though I think it is a good practise to use `$()` in most situations, it does not make backticks a *worse* thing. For practical purposes, one has to admit that they are much faster to type on the command line (2 keystrokes compared to at least 5, including `Shift`).

    @rozcietrzewiacz Your latter remark is probably true for most keyboards but `$( )` is definitely easier to type than `\` \`` at least on a French keyboard.

    @KhajaMinhajuddin You can nest backticks, but you need to escape the 2nd level of backticks, & 2nd level nesting you need 3 backticks, 3rd level nesting 5 backticks, 4th level 7, &c.

    diagram is really awesome :)

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM