我想做的是调用 PS1
中的函数更新函数内的变量。然后我喜欢使用该变量向 PS1 添加另一行。就像下面这样:
my_func(){
var="_RED_"
echo "hello in red"
}
PS1="\[\033]0;\w\007\]"
PS1+='$(my_func)'
if [ $var = "_RED_" ]; then # here I want to use that var
PS1+="\[$(tput setaf 124)\] red"
fi
这样做的原因是为了带上不可打印的字符\[
和\]
超出了防止由 \[ \]
引起的长行重叠的功能
最佳答案
您绝对可以更新 shell 函数内的全局变量 - 函数内的所有赋值都会修改全局变量,除非使用local
或declare
变量创建一个新范围。
但是,这里的问题是,您没有在与稍后尝试读取 var
的代码相同的 shell 进程中运行您的函数(尽管无论它实际上是“稍后”还是不是一个单独的问题)!当您使用命令替换($(my_func)
中的 $()
)时,您正在创建一个新的 fork 子进程来运行该函数。当该子进程退出时,对其所做的所有变量值更改都会随之丢失。
但是,您可以通过根本不使用命令替换来解决这个问题。考虑下面的代码,它使用 PROMPT_COMMAND
Hook 来分配 PS1
:
# code to run before each time a prompt is printed
PROMPT_COMMAND='build_ps1_func'
# rewrite your function to write to a named variable, not stdout
my_func(){
local outvar=$1; shift # named variable to write stdout to
var="_RED_" # hardcoded global to update, per question
printf -v "$outvar" '%s' "hello in red"
}
build_ps1_func() {
local your_str # define your_str as a local variable
my_func your_str # call my_func, telling it to write output to your_str
PS1="\[\033]0;\w\007\]"
PS1+="$your_str"
if [ $var = "_RED_" ]; then # using that variable here
PS1+="\[$(tput setaf 124)\] red"
fi
}
关于bash - 更新 bash 函数中的变量并在提示符中使用它 (PS1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37378803/