Bash – Understanding quotes in a bash conditional instruction

bashquoting

My friend is messing around with Bash scripts and he wanted me to take a look at them (he had another friend do it for him). One of the commands is

if [ "`pidof transmmission-gtk`"=0 ];

what exactly is the significance of the ` (backquote) before the pidof, especially when it's itself wrapped within double quotes?

For reference it's for the disper resolution package. I don't really use bash that much so that's why I ask.

Best Answer

The backquotes mean command substitution: the result of expanding `pidof transmission-gtk` is the output from running the command pidof transmission-gtk. An alternate way of writing `pidof transmission-gtk` is $(pidof transmission-gtk), and that alternate way is recommended (it has no downsides and it avoids issues when the command inside the backquotes itself contains quotes).

The double quotes around that prevent the result of the command substitution from being split into separate words and interpreted as wildcard patterns. If you're just starting with shell scripting, don't worry about this, just remember to always put double quotes around command substitutions. The same goes for variable substitutions, e.g. always write "$foo", never plain $foo.

This snippet as written doesn't make any sense: the test contains a single word, which will be something like =0 (if there is no running transmission-gtk process) or 1234=0 (if there is a matching process) or 123 456=0 (a single word in shell terminology, even if it happens to contain a space). A single word in a test is always considered true. To test whether a string is equal to another string, write [ "string1" = "string2" ] (there must be a space on each side of the brackets, and on each side of the operator). To test for numerical equality, use the -eq operator, e.g. [ 1 -eq 01 ] is true.

Here, there are two equivalent ways of testing whether there is a running transmission-gtk process:

  • Test whether the output is empty:

    if [ -z "$(pidof transmission-gtk)" ]; then …
    
  • Test whether the return status of the pidof is nonzero, indicating failure. Since the output of the command is not used, redirect it to /dev/null (the great void).

    if ! pidof transmission-gtk >/dev/null; then
    
Related Question