0

I am trying to read a variable with spaces on prompt and trying to use in a for loop.,

For example:

Enter the items to read separated by space...  
apple orange kiwi  
read items  

for i in "$items"  
do  
echo $i  
...(additional operations)....  
done  

But shell does take the first item - apple here. What am I missing here.

1
  • What shell are you using, bash? With what you have, I'd expect your loop to run once, and the value of $i to be "apple orange kiwi". Try removing the quotes from "$items" and see if that gets you closer to what you're expecting. Commented May 8, 2024 at 23:06

1 Answer 1

0

remove the double quotes around the $items:

items="apple orange kiwi"

for i in $items
do
  echo $i
done

double-quotes in bash are a way to designate "this is one string, treat it as such" so when you do for i in "$items" it expands $items and becomes "apple orange kiwi" but for in bash by default takes multiple strings and loops over them.

That is also why the initial items definition needs double quotes: variable definition in bash takes a single string, not multiple

3
  • Unfortunately this does not work and it shows up like "apple when it prints., Only the first string is used Commented May 9, 2024 at 17:00
  • @sabarishtr Works fine for me. I suspect you may using an editor that makes double quotes into the Unicode "LEFT DOUBLE QUOTATION MARK", which shell will not recognise as ASCII quotes. Commented May 9, 2024 at 22:18
  • @sabarishtr yea try another editor. Maybe kate?
    – dzervas
    Commented May 10, 2024 at 18:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.