Abdul Manaf
Abdul Manaf

Reputation: 4888

reading a file using shell script

I have a text file named sqlfile, with the following content:

a.sql
b.sql
c.sql
d.sql

What I want is that to store them in variables and then print using for loop. But here I get only d.sql in the output of the script.

The script:

#!/bin/bash

while read line
do
files=`echo $line`
done < /home/abdul_old/Desktop/My_Shell_Script/sqlfile

for file in $files
        do
                echo $file
        done

Upvotes: 5

Views: 18575

Answers (6)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10673

All you have to do is:

readarray myData < sqlfile

This will put file lines into an array called myData
Now you can access any of these lines like this:

printf "%s\n" "${myData[0]}" #outputs first line
printf "%s\n" "${myData[2]}" #outputs third line

And you can iterate over it:

for curLine in "${myData[@]}"; do
    echo "$curLine"
done

Note that these lines would contain \n character as well. To remove trailing newlines you can use -t flag like this:

readarray -t myData < sqlfile

readarray is a synonym to mapfile. You can read about it in man bash

Upvotes: 0

John
John

Reputation: 1791

Using read is fine but you have to set the IFS environment variable first else leading and trailing white space are removed from each line: Preserving leading white space while reading>>writing a file line by line in bash.

Upvotes: 0

Odobenus Rosmarus
Odobenus Rosmarus

Reputation: 5998

That's right, you assifn last value to "files"

You must use for instance += instead of =

#!/bin/bash

while read line
do
files+=`echo " $line"`
done < /home/abdul_old/Desktop/My_Shell_Script/sqlfile

for file in $files
        do
                echo $file
        done

Upvotes: 0

hhwangcocora
hhwangcocora

Reputation: 65

I think you need to make the "files" as array. otherwise, as soon as the while finishes, "files" stores the latest "line". try:

files=( "${files[@]}" $line )

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 755064

while read line
do files="$files $line"
done < /home/abdul_old/Desktop/My_Shell_Script/sqlfile

or

files=$(</home/abdul_old/Desktop/My_Shell_Script/sqlfile)

or

files=$(cat /home/abdul_old/Desktop/My_Shell_Script/sqlfile)

You're doing way too much work in your loop.

The middle alternative works with bash; the other two work with most shells. Prefer $(...) to back-quotes.

This code assumes there are no spaces in file names to mess things up. If you do use blanks in file names, you have to work marginally harder - see the array-based solution by SiegeX

Upvotes: 5

SiegeX
SiegeX

Reputation: 140547

A variable can only hold one element, what you want is an array

#!/bin/bash

while read line
do
  files+=( "$line" )
done < /home/abdul_old/Desktop/My_Shell_Script/sqlfile

for file in "${files[@]}"
do
  echo "$file"
done

Upvotes: 6

Related Questions