Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

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 ""

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.