Do I need to quote command substitutions?

后端 未结 3 992
借酒劲吻你
借酒劲吻你 2021-01-05 22:44

According to the Google Shell Style Guide, I should:

Always quote strings containing variables, command substitutions, spaces or shell meta characters

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 23:25

    When not to quote a command substitution?

    Answer: When you want the output of the command substitution to be treated as separate arguments.

    Example:

    We want to extract specific packets (packet numbers 1, 5, 10 and 20) from a .pcap file. The relevant command is the following:

    editcap -r capture.pcap select.pcap 1 5 10 20
    

    (Source to the command)

    Now, we want to extract random packets from the file. To do that, we will use shuf from GNU Coreutils.

    shuf -i 0-50 -n 4
    8
    24
    20
    31
    

    The command above has generated 4 random numbers between 0 and 50.

    Using it with editcap:

    editcap -r source.pcap select.pcap "$(shuf -i 0-50 -n 4)"
    editcap: The specified packet number "1
    34
    4
    38" isn't a decimal number
    

    As you can see, quoting the command substitution has resulted in the output string of the shuf to be treated as a single big string, including the newlines and whatnot as well. That is, putting quotes has resulted in the equivalent of the following command:

    editcap -r source.pcap select.pcap "1
    34
    4
    38"
    

    Instead, we want Bash the chop the output of shuf and insert this chopped output as separate arguments to editcap. Omitting the quotes accomplishes that:

    editcap -r source.pcap select.pcap $(shuf -i 0-50 -n 4)
    

提交回复
热议问题