read命令说明
如果变量名给出,则使用IFS变量对该行进行分词,并将每个单词分配给一个变量。如果存在比变量更多的单词,则将剩余的单词全部分配给最后一个单词。
read中 -d参数用来分隔行,IFS用来分隔词,所以并不矛盾。
Option Description
-a <ARRAY> read the data word-wise into the specified array <ARRAY> instead of normal variables
-d <DELIM> recognize <DELIM> as data-end, rather than <newline>
-e on interactive shells: use Bash's readline interface to read the data
-i <STRING> preloads the input buffer with text from <STRING>, only works when Readline (-e) is used
-n <NCHARS> reads <NCHARS> characters of input, then quits
-N <NCHARS> reads <NCHARS> characters of input, ignoring any delimiter, then quits
-p <PROMPT> the prompt string <PROMPT> is output (without a trailing automatic newline) before the read is performed
-r raw input - disables interpretion of backslash escapes and line-continuation in the read data
-s secure input - don't echo input if on a terminal (passwords!)
-t <TIMEOUT> wait for data <TIMEOUT> seconds, then quit (exit code 1). Fractional seconds ("5.33") are allowed since Bash 4. A value of 0 immediately returns and indicates if data is waiting in the exit code. Timeout is indicated by an exit code greater than 128. If timeout arrives before data is read completely (before end-of-line), the partial data is saved.
-u <FD> use the filedescriptor number <FD> rather than stdin (0)
这里有几个需要注意点的,所以当初卡在了这一块
read有分隔字符串的功能,如果我想分隔一个字符串 类似这样的”1\n2\n3\n-“ 这里我用-做行分隔符,因为’\n’字符用来做词分隔符了,这里使用有以下误区。
#误区一
echo -e "1\n2\n3\n4\n-" | IFS=$'\n' read -d '-' file1 file2 file3 file4
echo "=$file1="
echo "=$file2="
echo "=$file3="
echo "=$file4="
#结果
==
==
==
==
#One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option
#这里是因为手册中说了read 支持的是标准输入,这里用了管道当然是不行的。
#误区二
IFS=$'\n' read -d '-' file1 file2 file3 file4 <<< "1\n2\n3\n4\n-"
echo "=$file1="
echo "=$file2="
echo "=$file3="
echo "=$file4="
#结果
=1n2n3n4n=
==
==
==
#这里算是出来结果了,但是并不是我们想要的,因为IFS中设置的是'\n'。
#但是字符串中的'\n'被解释为了两个字符,而IFS中的'\n'是单个字符,所以查询不到'\n'这个分隔符。
#正解
echo -e "1\n2\n3\n4\n-" | while IFS=$'\n' read -d '-' file1 file2 file3 file4
do
echo "=$file1="
echo "=$file2="
echo "=$file3="
echo "=$file4="
done
#结果
=1=
=2=
=3=
=4=
这里还有一个点需要注意 就是空格字符。
echo -e " hello world " | while read file1
do
echo "=$file1="
done
#输出
=hello world=
#这里把开头和结尾的空格舍去了。如果不想舍去空格可以这样来。
echo -e " hello world " | while IFS= read file1
do
echo "=$file1="
done
#输出
= hello world =
如果 read后的变量数小于分隔后的,会把他合并到一个变量中,当然他中间的空格就不会舍弃了。
echo -e " hello world " | while read file1 file2
do
echo "=$file1="
echo "=$file2="
done
=hello=
=world=
这里有一个隐性规定就是 如果分隔符为空格,那么头尾的可以省去,但是如果是其他类型的字符分隔,那么不会省去。如下
#!/bin/bash
IFS=' ' read -d '-' var1 var2 <<< " 123 -"
printf "%s\n" "var1=$var1= var2=$var2="
IFS='|' read -d '-' bar1 bar2 <<< "|123|-"
printf "%s\n" "bar1=$bar1= bar2=$bar2="
#结果
var1=123= var2==
bar1== bar2=123=
参考链接
http://wiki.bash-hackers.org/commands/builtin/read
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 68813175@qq.com