bash shell script
I have $L开发者_JAVA百科IST variable that contains few lines and some of the lines has spaces, but I need to take that as one vs two arguments inside of my loop, how would I do that?
\#!/bin/bash
LIST="test1
test 2"
for i in $LIST; do
echo $i;
done
this will produce me 3 lines, but I want it to produce 2 as test1 on first line and test 2 on second
#!/bin/bash
LIST="test1
test 2"
while read i
do
echo "[$i]"
done <<< "$LIST"
Thanks to [] characters we can see that the loop was evaluated twice.
IFS controls what's treated as a word break when variables are expanded (e.g. in the for
command):
LIST="test1
test 2"
saveIFS="$IFS"; IFS=$'\n'
for i in $LIST; do
IFS="$saveIFS" # This is only needed if something in the loop depends on IFS
echo "$i"
done
IFS="$saveIFS"
Just for fun and educational purposes: No need for bashisms like <<<
here. Understand that echo keeps newlines in quoted strings and just read line by line as follows:
#!/bin/sh
LIST="test1
test 2"
echo "$LIST" |
while read -r line; do
echo "[$line]"
done
$ ./x.sh
[test1]
[test 2]
There, 100% POSIX shell compatible!
No need to change IFS. Just need to quote your variable
LIST="test1
test 2"
for i in "$LIST"; do
echo "$i";
done
精彩评论