Reading a file using a shell script

I have a text file called sqlfile with the following contents:

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

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

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 
+4
source share
6 answers

A variable can contain only one element, you need 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 
+6
source
 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 do too much work in your cycle.

The middle alternative works with bash ; the other two work with most shells. Prefer $(...) for backticks.

This code assumes that there are no spaces in the file names to ruin everything. If you use spaces in file names, you will have to work a little harder - see SiegeX array-based solution

+5
source

I think you need to make the "files" as an array. otherwise, as soon as the time runs out, the β€œfiles” save the last β€œline”. try:

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

That's right, you subsequently add "files"

You should use, for example, + = 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 
0
source

Using the read is okay, but you have to set the IFS environment variable, and the first and previous spaces are removed from each line: Maintain leading space when reading β†’> file line by line in bash .

0
source

All you have to do is:

 readarray myData < sqlfile 

This will put the lines of the file into an array called myData
Now you can access any of the following lines:

 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 will contain the \n character. To remove trailing newlines, you can use the -t flag as follows:

 readarray -t myData < sqlfile 

readarray is synonymous with mapfile . You can read about it in man bash

0
source

Source: https://habr.com/ru/post/1391198/


All Articles