Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best quotes practice when it doesn't matter? [closed]

Tags:

bash

If I want to something like:

foo="bar baz"
foo='bar baz'

Is it best practice to use double-quotes or single-quotes?

like image 900
Tyilo Avatar asked Jan 30 '26 05:01

Tyilo


1 Answers

It depends, as usual:

  • Single quotes cannot contain other single quotes, and there's no way to escape them. For this reason they should only be used for 'simple' text.
  • Double quotes support useful things like brace expansion (echo "${USER} uses ${LANG#*.} encoding"), but you can't include escape sequences in them. That means you generally won't be able to see the difference between for example "[space][tab]" and "[tab]" strings.
  • Dollar-single quoted strings are much like double-quoted strings, but can contain control characters. My personal favorite for unit testing:

    $ echo -n $'--$`!*@\a\b\E\f\r\t\v\\\'"\360\240\202\211 \n' | uniname -bcepu
    glyph   name
    -      HYPHEN-MINUS
    -      HYPHEN-MINUS
    $      DOLLAR SIGN
    `      GRAVE ACCENT
    !      EXCLAMATION MARK
    *      ASTERISK
    @      COMMERCIAL AT
            BELL
            BACKSPACE
            ESCAPE
            FORM FEED (FF)
            CARRIAGE RETURN (CR)
            CHARACTER TABULATION
            LINE TABULATION
    \      REVERSE SOLIDUS
    '      APOSTROPHE
    "      QUOTATION MARK
    𠂉      Unknown character in range CJK Unified Ideographs Extension B
            SPACE
            LINE FEED (LF)
    

If you want to know if you should use $' quoting or not for a variable, try sending it to printf %q:

$ var=foo
$ printf %q "$var"
foo
$ var="foo
> bar"
$ printf %q "$var"
$'foo\nbar'
like image 149
l0b0 Avatar answered Jan 31 '26 20:01

l0b0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!