bash - 更新 bash 函数中的变量并在提示符中使用它 (PS1)

标签 bash shell scripting sh

我想做的是调用 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 函数内的全局变量 - 函数内的所有赋值都会修改全局变量,除非使用localdeclare变量创建一个新范围。

但是,这里的问题是,您没有在与稍后尝试读取 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/

相关文章:

xml - Shell 脚本,解析 XML 片段

linux - 如何打开 xterm -e 'command' 并保留已声明的函数?

linux - 根据文件名获取两个日期之间的日志

bash - 继续从 tcp 服务器读取数据,直到收到特定消息

bash - 如何在 Bash 中跳出循环?

linux - 删除 shell 命令后的换行符

python - 在 Python 中快速执行动态代码的可能性

linux - 着色尾输出 bash

linux - LD_LIBRARY_PATH 未链接库

linux - shell脚本不运行