Sea*_*red 4 bash process-substitution subshell variable
我正在尝试远程运行脚本并使用其标准输出来填充变量。我这样做是为了避免临时文件。
这是我正在尝试的模式:
var=$(bash <(curl -fsSkL http://remote/file.sh))
echo "var=${var}"
Run Code Online (Sandbox Code Playgroud)
我正在测试这种模式而不curl使用cat:
var=$(bash <(cat ./local/file.sh))
echo "var=${var}"
Run Code Online (Sandbox Code Playgroud)
就语法而言,这应该是相同的。 ./local/file.shcontains echo hello,所以我希望var包含 value hello,但唉,执行上述结果如下:
var=$(bash <(curl -fsSkL http://remote/file.sh))
echo "var=${var}"
Run Code Online (Sandbox Code Playgroud)
如何在不使用临时文件的情况下实现我的目标?
Kus*_*nda 13
这些是bash当 shell 在 POSIX 模式下运行时尝试执行进程替换时遇到的错误。在bash外壳不支持POSIX模式过程中换人。
bash 将在 POSIX 模式下运行
set -o posix 已被使用,或sh.我的预感是你有一个脚本,test.sh你正在运行sh test.sh或者有一个#!/bin/shhashbang 行,而你sh恰好是bash. 另一种可能性是,该脚本不具有#!直插可言的,它是由调用bash-as-sh在一些其他的方式。
相反,请确保您的test.sh脚本正在被调用bash。
例子:
$ cat script.sh
echo hello
Run Code Online (Sandbox Code Playgroud)
$ cat test.sh
var=$(bash <( cat script.sh ))
printf 'var="%s"\n' "$var"
Run Code Online (Sandbox Code Playgroud)
$ bash -o posix test.sh
test.sh: command substitution: line 2: syntax error near unexpected token `('
test.sh: command substitution: line 2: `bash <( cat script.sh ))'
var=""
Run Code Online (Sandbox Code Playgroud)
$ bash test.sh
var="hello"
Run Code Online (Sandbox Code Playgroud)
如果您想在test.sh脚本中使用 POSIX以可移植的方式执行此操作sh:
var=$( cat script.sh | bash )
printf 'var="%s"\n' "$var"
Run Code Online (Sandbox Code Playgroud)
这会影响bash进程cat在其标准输入上读取 的输出,这与您的进程替换变体(单独留下标准输入)不太相同。如果内部bashshell 执行的脚本从其标准输入中读取任何形式的数据,这很重要。
如果您需要bash单独保留shell 的标准输入(因为您需要从中读取),您可能会假设它mktemp可用并使用
var=$( tmpfile=$(mktemp); cat script.sh >"$tmpfile" && bash "$tmpfile"; rm -f "$tmpfile" )
printf 'var="%s"\n' "$var"
Run Code Online (Sandbox Code Playgroud)
wherecat script.sh理解为以后替换为你的curl命令。
如果您对处理文件描述符感到满意,您还可以在调用bashshell之前将文件描述符 3 设为标准输入描述符的副本,然后让获取的脚本从中读取:
var=$( exec 3<&0; cat script.sh | bash )
printf 'var="%s"\n' "$var"
Run Code Online (Sandbox Code Playgroud)
然后script.sh脚本将用于read -u 3从原始标准输入流中读取,或utility <&3将该输入流重定向到另一个实用程序。
| 归档时间: |
|
| 查看次数: |
1531 次 |
| 最近记录: |