2

In a script, I am passing variables to an assembler (NASM), and I want these to be handled as strings by the assembler. That means the program being executed should receive pairs of quotes around literal text. (To ensure handling as text, in some cases I put nested quotes around a string, like "'...'", that is, double quotes around single quotes around content.) When no text is to be passed (the empty string), two quotes without content between them should be passed.

I am using Parameter Expansion, specifically the Use Default Values kind, which is described as follows in the bash manual page:

${parameter:-word}

Use Default Values. If parameter is unset or null, the expan‐ sion of word is substituted. Otherwise, the value of parameter is substituted.

This is an example of where I'm using the Use Default Values parameter expansion: https://bitbucket.org/ecm/ldebug/commits/f9b7def927cab0568e30dd9480e9d9b31f46b99f#Lsource/mak.shT58 -D_REVISIONID_SYMSNIP="${build_revision_id_symsnip:-''}"

Testing this, it seems like the double quotes around word are allowed, but not needed.

$ bash --version
GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ foo=bar
$ baz=""
$ echo "${foo:-''}"
bar
$ echo "${foo:-"''"}"
bar
$ echo "${baz:-''}"
''
$ echo "${baz:-"''"}"
''
$ echo "${baz:-' '}"
' '
$ echo "${baz:-"' '"}"
' '
$ echo X"${baz:- }"Y
X Y
$ echo X"${baz:-" "}"Y
X Y
$ 

So, should I include the double quotes around word or is it fine, or even preferred, without?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
ecm
  • 2,583
  • 4
  • 21
  • 29
  • 1
    It seems to make a difference sometimes: cf. `"${baz:-'}"` and `"${baz:-"'"}"`. – choroba Jul 06 '19 at 19:49
  • That's true. `:-'` is treated as an opening quote and the shell asks for a further line. `:-"'"` works as expected. – ecm Jul 06 '19 at 19:55
  • 1
    The default `word` inside parameter expansion is treated like any other parameter value, that is it can be expanded as well. Means escaping and globing rules applies. If the default parameter expansion is between double quotes `"`, then rules for text beween double quotes applies. Spaces will not be treated as field separators, but identifiers `$varname` or `${varname}` or sub shells `$(command)` will be expanded, so you will need to escape these markers or use single quote `'` to enclose your default value. – Léa Gris Jul 06 '19 at 19:57
  • Using pairs of single quotes in the `word` always seems to pass the single quotes to the actual text as literals, instead of only using them for quoting. – ecm Jul 06 '19 at 20:02

0 Answers0