'How to add $USER inside of nested quotes? [duplicate]

I have a variable:

my_var="$('/some/path/to/username/more/path' 'and/something/else')"

and I want to change it to be more generic like:

my_var="$('/some/path/to/${USER}/more/path' 'and/something/else')" 

but that doesn't work. How can I get the user inside of there?



Solution 1:[1]

The problem is that inside a single quoted string nothing is treated with a special meaning. This makes them good for scripting, eg. grep '^pattern$' ... and sed 's/abc$/def/'.

You can use double quotes instead.

$(...) is a command substitution. Is that correct? If so, then you can nest double qoutes:

my_var="$("/some/path/to/${USER}/more/path" 'and/something/else')" 

This should be interpreted as two set of quotes, so the outer double quotes, isn't stopped at the first inner quote:

my_var="$(                                                      )" # First set of quotes
          "/some/path/to/${USER}/more/path"                        # Second set of quotes

When assigning a variable, you don't need to wrap the expression in double quotes, so:

my_var=$("/some/path/to/${USER}/more/path" 'and/something/else')

would also be fine in this case. Most other cases you should always wrap parameter expansions ($abc), command substitutions ($(...)) etc. in double quotes as to avoid word splitting and pathname expansions.

However to me it seems like you are trying to create an array instead?

$ my_var=("/some/path/to/${USER}/more/path" 'and/something/else')
$ echo "${my_var[0]}"
/some/path/to/and/more/path

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas Louv