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 - 内核模块(.ko 文件)移植到 DLL 导出符号

bash - 使 bash 脚本自跟踪的更好方法?

linux - ssh并执行命令而不退出

linux - 如何在 bash 中创建动态命令?

java - 如果命令太长,如何获取linux上的java进程命令?

javascript - 环境变量 - 未定义

jar - 通过应用使用的jar文件传递环境变量

node.js - 这个在 linux 中将环境变量传递给 node 的例子是如何工作的?

linux - 分区的开始和结束扇区?

linux - 从 linux shell 中的 'ftp' 命令获取退出状态代码