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
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
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
使用read很好,但你必须首先设置IFS环境变量,否则从每行中删除前导和尾随空格: 在读取时保留前导空格>>在bash中逐行写入文件 。
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
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 )
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.