user2118349
user2118349

Reputation: 137

passing strings to while loop

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.

Upvotes: 2

Views: 2001

Answers (4)

DevZer0
DevZer0

Reputation: 13525

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

#!/bin/bash


for x in "var1" "var2"
do
   echo $x
done

Upvotes: 6

jaypal singh
jaypal singh

Reputation: 77075

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

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

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.

Upvotes: 2

perreal
perreal

Reputation: 97918

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

Upvotes: 1

Related Questions