0

Why is this coding getting "ambiguous redirect" error for reading two variables in parallel? I must use while or for loop, can't use "paste"

#!/bin/bash
export fname="Adam Baden Caydin"
export lname="Sam Tam Uam"
while read first_name <$fname && read last_name <$lname
do
echo $first_name "    :    " $last_name
echo "doing some processing here..... "
done 

Error: ./f1.sh: line 4: $fname: ambiguous redirect

Replacing last line "done" with gives same result

done <<< "$fname $lname"

Error: ./f1.sh: line 4: $fname: ambiguous redirect

Expected Output

Adman Sam
Baden Tam
Caydin Uam
4
  • I don't think you can do this with read. Why not make them arrays? Commented Sep 21, 2017 at 21:16
  • read reads a whole line, not one word at a time. Commented Sep 21, 2017 at 21:17
  • 1
    Why are you exporting the variables? Commented Sep 21, 2017 at 21:17
  • @UlisesAndréFierro What variable is he re-declaring? Commented Sep 21, 2017 at 21:26

1 Answer 1

3

read expects each input to be on a separate line, so you have to replace the spaces with newlines. And to read the names in parallel, you need to combine the corresponding items into the same line of input. You can do this with the paste command.

paste <(tr ' ' '\n' <<<"$fname") <(tr ' ' '\n' <<<"$lname") | while read first_name last_name
do
echo $first_name : $last_name
done

Oops, didn't notice the constrain against using paste. Another solution is to use arrays instead of strings:

fname=(Adam Baden Caydin)
lname=(Sam Tam Uam)
i=0
for first_name in "${fname[@]}"
do
    last_name=${lname[$i]}
    echo $first_name : $last_name
    ((i++))
done
Sign up to request clarification or add additional context in comments.

5 Comments

I like this, but OP said "can't use paste."
@sjnarv Thanks, added an array solution as well.
thanks for solution for paste, it works :) funny thing is that it doesn't work while /location/filename.csv /location/filename2.csv somehow it's not catching that space between them. going to research this. thanks for great solution :)
edit: i think it's because i have null value instead of white space because I did a run try and it worked, will post something when I get solution.
I thought you weren't allowed to use paste. I don't understand what those filenames are for, I thought the whole point is that the data is in variables, not files.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.