How do I learn how to get quoting right in bash?

后端 未结 3 628
不思量自难忘°
不思量自难忘° 2021-01-06 16:40

I\'m constantly confused by the rules for quoting and evaluating when I\'m writing bash scripts. I know some of the basics, like the difference between \'\' and \"\" and ``,

3条回答
  •  失恋的感觉
    2021-01-06 17:14

    Use singlequotes '' for quoting raw text (even backslashes do not escape anything in singlequotes):

    > echo '\'
    \
    > echo '$PATH'
    $PATH
    

    Use doublequotes "" for quoting text which contains things the shell shall evaluate like variables ($bla), subshell calls ($(ls)), and evaluations ($((5 + 3))).

    > echo "$PATH"
    /home/alfe/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
    > echo "$(ls | tail -1)"
    bla
    > echo "$((5 + 3))"
    8
    

    Use backticks `` if for some reason you cannot use $() (e. g. in the rare cases where you have to you sh instead of bash. Normally use $() to gather the output of a subshell into the current command.

    > echo "$(ls | tail -1) is the last file in the current dir."
    bla is the last file in the current dir.
    

    One of the main problems I run into with bash code of other people is missing doublequotes around something which often is just a word but in rare cases may be more than one word, or which can contain special characters. So use doublequotes wherever they are possible.

    > a="four    spaces"
    > echo $a
    four spaces
    > echo "$a"
    four    spaces
    

提交回复
热议问题