linux - 保留返回值并且不从子 shell 运行

标签 linux bash environment-variables scoping subshell

我正在调用一些将 VARIABLE 设置为某个值并返回另一个值的函数。我需要保留 VARIABLE 的值并将函数的返回值分配给另一个 VAR。这是我尝试过的:

bar() {
        VAR="$(foo)"
        echo $VARIABLE >&2
        echo $VAR >&2
}

foo() {
        VARIABLE="test"
        echo "retval"
}
bar

但是它打印

retval

有办法吗?

最佳答案

ksh 有一个方便的非子脱壳命令替换结构:

#!/bin/ksh
foo() {
  echo "cat"
  variable="dog"
}
output="${ foo }"
echo "Output is $output and the variable is $variable"

bash 和其他 shell 中,您必须改为通过临时文件:

#!/bin/bash

foo() {
  echo "cat"
  variable="dog"
}

# Create a temp file and register it for autodeletion
file="$(mktemp)"
trap 'rm "$file"' EXIT

# Redirect to it and read it back
foo > "$file"
output="$(< "$file")

echo "Output is $output and the variable is $variable"

关于linux - 保留返回值并且不从子 shell 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50427597/

相关文章:

Linux 命令行不将 true 作为命令参数

bash - 递归地在zip文件列表中grep一个模式

java - 安装 Java SE 和 Java EE - 设置 JVM

windows - 访问 Windows 服务器上的特定用户环境变量

linux - 使用从其他文件复制的增量序列和名称字段在单个文件中多次复制模板

asp.net - ASP.NET web.config 文件中的环境变量

linux - 如何在 Linux 中检测正在用于充电的 USB 端口?

linux - 在 Linux 中动态查看日志文件

linux - 如何从 shell 中提取文件中第一个空字符之后的所有内容

linux - 在 linux/bash 中添加命令行参数