我正在调用一些将 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/