LamaEu LamaEu - 6 months ago 18
Bash Question

Reading lines from a different shell using pipeline

I'm receiving to my main script an argument($1) which is a file I should read the lines of. I then need to do some actions on these lines, and return them "fixed"(actions have been done on them, they're new lines). I do this like that:

cat "$1" | isValidParameters


isValidParameters
returns new lines, which I now want to read into an array in my main script. I was thinking of doing something like:

while read -r -a arr; do
:
done < $(cat "$1" | isValidParameters)


but this doesn't seem to work. How can I read the lines I receive from
isValidParameters
into an array in my main script so that I can do actions on them there? Thank you.

-----------------------------------------------------

I have edited my code as @chepner suggested:

while IFS= read -r line; do
arr+=("$line")
done < <(isValidParameters < "$1")

printf "%s\n" "${arr[@]}"


And when I run this, I get no output at all.
What I run is:
./getApartments dos > output.txt


NOTE: dos is not a real file in my directory, those
isValidParameters
should print:
File is missing
.

Here is
isValidParameters
:

#!/bin/bash
PATH=$PATH:.

if(($# != 1 && $# != 3)); then
echo "Illegal or missing parameters"
exit 1
fi

if [[ !(-f $1) ]]; then echo "File is missing";
exit 1
fi

#find . $1 \*.flat -print

function search_file() {
#echo "$1"

for line in "$1"/*; do
if [[ $line == *.flat && -f "$line" ]]; then
echo "$line"
fi

if [[ $line == *.flat && -d "$line" ]]; then
search_file "$line"
fi
done
}

while read line; do
if [[ $line == *.flat && -f "$line" ]]; then
echo "$line"
fi

if [[ $line == *.flat && -d "$line" ]]; then
search_file "$line"
fi
done < "$1"

Answer

read -a does not read multiple lines into an array; it splits a single line into fields and populates array with those fields. If you are using bash 4, you can use the readArray command:

readArray -t arr < <(isValidParameters < "$1")

or append to the array line by line in earlier versions of bash:

while IFS= read -r line; do
    arr+=("$line")
done < <(isValidParameters < "$1")
Comments