rag*_*jan 3 bash rhel io-redirection read here-string
我正在尝试将 python 脚本的输出重定向为交互式 shell 脚本的输入。
测试文件
print('Hello')
print('world')
Run Code Online (Sandbox Code Playgroud)
说 test.py 如上所述打印“Hello world”,它使用Here 字符串重定向提供给两个变量,如下所示
交互式脚本: read a b <<< `python3 test.py`
这在 Rhel 8 服务器中没有按预期工作,而在 Rhel 7 中工作正常
雷尔8:
tmp> read a b <<< `python3 test.py`
tmp> echo $a $b
Hello
tmp> cat /etc/redhat-release
Red Hat Enterprise Linux release 8.3 (Ootpa)
Run Code Online (Sandbox Code Playgroud)
变量b在rhel 8中为空
雷尔7:
tmp> read a b <<< `python3 test.py`
tmp> echo $a $b
Hello world
tmp> cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.8 (Maipo)
Run Code Online (Sandbox Code Playgroud)
而read & Here 字符串在两种情况下都可以正常工作,如下所示
tmp> read a b <<< Hello world"
tmp> echo $a $b
Hello world
Run Code Online (Sandbox Code Playgroud)
Sté*_*las 10
read a b读取来自两个字一个线(由分隔的多个字$IFS与转义字符和字线和分隔符\)。
您的python脚本输出 2 行。
旧版本bash曾在一个错误cmd <<< $var或cmd <<< $(cmd2)正在申请分词,以扩大$var和$(cmd2)与空间也弥补了下面的字符串的内容加入,结果元素后面(见例如为什么切不能使用bash,而不是zsh的?)。
这是固定在4.4版本,这可以解释为什么你没有得到什么,你希望的任何更长的时间。
要将命令输出的前两行读入$a和$b变量中bash,请使用:
{
IFS= read -r a
IFS= read -r b
} < <(cmd)
Run Code Online (Sandbox Code Playgroud)
或者(不在交互式 shell 中):
shopt -s lastpipe
cmd | {
IFS= read -r a
IFS= read -r b
}
Run Code Online (Sandbox Code Playgroud)
或者没有lastpipe:
cmd | {
IFS= read -r a
IFS= read -r b
something with "$a" and "$b"
}
# $a and $b will be lost after the `{...}` command group returns
Run Code Online (Sandbox Code Playgroud)
要将命令输出的行与空格连接起来,请使用:cmd | paste -sd ' ' -。然后你可以这样做:
IFS=' ' read -r a b < <(cmd | paste -sd ' ' -)
Run Code Online (Sandbox Code Playgroud)
如果你喜欢。
您还可以使用以下命令将行读入数组元素:
readarray -t array < <(cmd)
Run Code Online (Sandbox Code Playgroud)
并将数组的元素与$IFS(默认为空格)的第一个字符与"${array[*]}".
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |