Bash字符串处理(与Java对照) - 5.字符串输入(读取字符串)(三)

2014-11-24 02:38:33 · 作者: · 浏览: 6
read -r LINE3; }
[root@web ~]# { read -r LINE1; read -r LINE2; read -r LINE3; } [root@web ~]# echo $LINE1
Some text here
[root@web ~]# echo $LINE2
with backslash \ here
[root@web ~]# echo $LINE3
dollar $HOME meet
[root@web ~]#

从Here Document读取
错误:read VAR < some string
EOF
正确:{ read VAR; } < some string
EOF
问题:为什么写在代码块中才能读取呢?

[root@web ~]# read VAR < > some string
> EOF
[root@web ~]# echo "$VAR"

[root@web ~]# { read VAR; } < > hello
> EOF
[root@web ~]# echo "$VAR"
hello
[root@web ~]#

从Here String读取
read VAR <<< "some string"
read VAR <<< "$STR"

[root@web ~]# read VAR <<< "some string"
[root@web ~]# echo $VAR
some string
[root@web ~]#


补充:关于 cat input.txt | read VAR 的问题
先说一下我对管道线的理解:管道线两侧的命令,前一个命令的输出(标准输出),将作为后一个命令的输入(标准输入)。两侧的命令都是在子进程中执行的,都有各自独立的地址空间,子进程会继承(复制)父进程所有的环境变量。子Shell(subshell)是一种特殊的子进程,它会继承(复制)父Shell的所有变量;对于非子Shell进程(外部命令),只有环境变量会被继承(复制)。但是,子进程一旦启动,它所有的变量只在它的进程空间中有效,它对变量的修改都是对自己范围之内的变量的修改,对父进程相同名称的变量是没有影响的。而子进程启动之后,它的父进程对父进程变量的修改,对子进程相同名称的变量也是没有影响的。
Advanced Bash-Scripting Guide: Chapter 3. Special Characters | 写道
|

pipe. Passes the output (stdout) of a previous command to the input (stdin) of the next one, or to the shell. This is a method of chaining commands together.

A pipe, as a classic method of interprocess communication, sends the stdout of one process to the stdin of another. In a typical case, a command, such as cat or echo, pipes a stream of data to a filter, a command that transforms its input for processing.

The output of a command or commands may be piped to a script.

A pipe runs as a child process, and therefore cannot alter script variables.

variable="initial_value"
echo "new_value" | read variable
echo "variable = $variable" # variable = initial_value

[root@web ~]# cat input.txt
Some text here
with backslash \ here
dollar $HOME meet

[root@web ~]# cat input.txt | read VAR
[root@web ~]# echo $VAR

上面的cat input.txt的输出将作为read VAR的输入。
[root@web ~]# cat input.txt | { read VAR; echo $VAR; }
Some text here
可以看到管道线后面的子Shell中确实读到了值。
[root@web ~]# echo $VAR

但父Shell中的相同变量不会改变。
[root@web ~]#

作者“Bash @ Linux