2

I am trying to pass two strings to a while loop but i forgot the syntax please help me out. This is what i am trying-

#!/bin/bash
while read line
do  
    echo "successful"
done < "var1" "var2" 
exit

I know i am doing something wrong here, i used to pass strings to while loop but i forgot the syntax. Please help me out here.

I am aware of -

#!/bin/bash
while read line
do
   echo "successful"
done < "file_containing_var1_and_var2"

but i want to pass strings and not file to while loop, Any help is appreciated.

4 Answers 4

6

< redirection operator only works with files. for your requirement use a for loop

#!/bin/bash


for x in "var1" "var2"
do
   echo $x
done
Sign up to request clarification or add additional context in comments.

Comments

4

To pass string to your while loop, you need to use herestring <<< notation.

$ while read line; do 
    echo "$line"
done <<< "This is my test line"
This is my test line

2 Comments

Hi JS, This is exactly what i wanted. can you please point out how do i pass more than one string here.
@user2118349 You are better off using a for loop as suggested by DevZer0, but if you must then you can do something like: $ while IFS=: read string1 string2; do printf "%s\n%s\n" "$string1" "$string2"; done <<< "this is my string":"this is another string"
2
printf "%s\n" "var1" "var2" |
while read line
do  
    echo "successful: $line"
done

The printf command echoes each argument on a line on its own.

Comments

1

You can pipe into a while loop:

#!/bin/bash
echo "var1" "var2" | while read line
do
    echo "successful: $line"
    set "$line"
    echo "v1: $1 v2: $2"
done

Output:

successful: var1 var2
v1: var1 v2: var2

2 Comments

Thanks perreal, jonathan and DevZero, Your answers added something new to my vault. Thanks for your time.
In case $line happens to begin with a hyphen, set -- $line (unquoted)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.