Passa al contenuto principale

2. Shell quotes

  1. Using quotes in a command affects the spaces:

    echo this is a      test
    echo "this is a      test"

    When the shell parses the first command it finds 4 arguments: "this", "is", "a", "test". Then it calls echo passing it these arguments.

    In the second case the quotes let the shell know that there is a single argument: "this is a test", and it passes to echo only one argument.

  2. Double quotes do not prevent variable expansion, but single quotes do:

    echo The total is $100.0
    echo "The total is $100.0"
    echo 'The total is $100.0'

    Bash reckognizes $1 as a special variable and tries to replace its value (which is empty). Using double quotes does not prevent Bash from expanding variables, we need single quotes for that.

  3. Double quotes do not prevent the shell expansions that start with a "$", but prevents the others:

    echo ~/*.txt {a,b} $(echo foo) $((2 + 2))
    echo "~/*.txt {a,b} $(echo foo) $((2 + 2))"
    echo '~/*.txt {a,b} $(echo foo) $((2 + 2))'

    They are useful for preserving the spaces, for example:

    echo $(cal)
    echo "$(cal)"
  4. We can also escape "$" by preceding it with "\":

    echo The balance is: $5.00
    echo The balance is: \$5.00
  5. The option -e of echo will also enable other escape sequences like \n (for a new line) and \t (for a tab):

    echo "a\nb"
    echo -e "a\nb"
    echo "a\tb"
    echo -e "a\tb"
Loading asciinema cast...