Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash difference between raw string and string in variable

Tags:

string

bash

shell

I wrote a little script in bash, but it only worked when I stored the string as a variable, and I'd like to know why. Here's the summary:

When I use the string itself, bash treats it as a single entity

for word in "this is a sentence"; do
    echo $word
done
# => this is a sentence

If I save the exact same string into a variable, bash iterates over the words

sentence="this is a sentence"
for word in $sentence; do
    echo $word
done

# => this
# is
# a
# sentence
  1. Why are these being treated differently?
  2. Is there a simple way to iterate through the words in the string without first saving the string as a variable?
like image 251
EthanP Avatar asked Oct 20 '25 11:10

EthanP


1 Answers

The quotes tell bash to treat a thing in quotes as a single parameter in a parameter list at the time the expression is evaluated. The quotes (unless protected with \ or ') are removed.

echo ""    # prints newlines, no quotes
echo '""'  # Print ""

export X='""'
env | grep X   # X contains ""

export X=""
env | grep X   # X is empty

When you use a variable, bash unpacks it as is (i.e. as if you typed the variable's contents in the variable's place). For a for-loop bash determines the list-elements to iterate over by separating the for-loop's parameters by whitespace, but treating (as always) quote-protected items a single parameter/list-element. Your variable contained no quotes -- items are treated as separate parameters.

like image 87
user48956 Avatar answered Oct 23 '25 01:10

user48956



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!