1

When bashing, I know that double quoting is sometimes necessary if an environment variable (EV) contains embedded spaces. Example: "$JACK" rather than $JACK. Sometimes it is recommended to use the syntax borrowed from substringing if the identifier of the EV is ambiguous. Example, because the EV is not $JACKA, $JACKAN, nor $JACKAND we would use curly braces with no substring indices to write ${JACK}ANDJILL.

It seems that double quotes can accomplish the same thing. Example: "$JACK"ANDJILL

In fact if we do nothing but echo the following demonstrates equivalence.

#!/bin/bash
TEXAS="asdf asdf"
FLORIDA="qwer""$TEXAS""qwer" # use quotes
echo $FLORIDA

ALABAMA="qwer"${TEXAS}"qwer" # use substring without indices
echo $ALABAMA

ARIZONA="qwer""${TEXAS}""qwer" # use both
echo $ARIZONA

MAINE="qwer"$TEXAS"qwer" # use neither
echo $MAINE

NEVADA="qwer""$TEXAS"qwer # last bit not quoted
echo $NEVADA

IDAHO="qwer"${TEXAS}qwer # last bit not quoted
echo $IDAHO

The output:

    qwerasdf asdfqwer
    qwerasdf asdfqwer
    qwerasdf asdfqwer
    qwerasdf asdfqwer
    qwerasdf asdfqwer
    qwerasdf asdfqwer

Are there bash statements/constructs where the substring trick cannot be substituted with double quotes?

1 Answer 1

1

Substring has more function, as the name says it can be used to take a substring of a variable.
For example

var='123456789'
echo ${var:2:4}

Will output

3456

While using array you have to use substring for accessing array variables.
For example

a[0]=0
a[1]=1
a[2]=2

echo $a will print 0.
echo "$a[1]" output 0[1]
So accessing array variable at location 1 as follows

echo ${a[1]}

This outputs 1

echo "${a[@]}" output all variable. ie 0 1 2 In these cases substring can't be repaced with ""

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .