如何根据旧定义重新定义 bash 函数?

tmo*_*hou 14 bash function

有什么方法可以根据旧定义重新定义 bash 函数?例如,我想将以下代码块添加到函数的序言中command_not_found_handle ()

# Check if $1 is instead a bash variable and print value if it is
local VAL=$(eval echo \"\$$1\")
if [ -n "$VAL" ] && [ $# -eq 1 ]; then
    echo "$1=$VAL"
    return $?
fi
Run Code Online (Sandbox Code Playgroud)

它目前在 /etc/profile.d/PackageKit.sh 中定义并由 bash 启动脚本提供。

这样我就可以在命令提示符下通过简单地输入变量名称来查询环境变量的值(并且假设不存在该名称的此类命令)。例如

user@hostname ~:$ LANG
LANG=en_AU.utf8
Run Code Online (Sandbox Code Playgroud)

我知道我可以复制并粘贴当前定义并在 中添加我自己的更改~/.bashrc,但我正在寻找一种更优雅的方式来重用代码。

实现我的目标或代码改进/扩展的更好方法也受到赞赏。

Gil*_*il' 14

您可以打印出函数的当前定义,然后将其包含在eval子句内的函数定义中。

current_definition=$(declare -f command_not_found_handle)
current_definition=${current_definition#*\{}
current_definition=${current_definition%\}}
prefix_to_add=$(cat <<'EOF'
  # insert code here (no special quoting required)
EOF
)
suffix_to_add=$(cat <<'EOF'
  # insert code here (no special quoting required)
EOF
)
eval "command_not_found_handle () {
  $prefix_to_add
  $current_definition
  $suffix_to_add
}"
Run Code Online (Sandbox Code Playgroud)

我发现另一种更清晰的方法是以新名称定义原始函数,并从您的定义中调用它。这仅在您不需要对原始定义的局部变量进行操作时才有效。

eval "original_$(declare -f command_not_found_handle)"
command_not_found_handle () {
  …
  original_command_not_found_handle
  …
}
Run Code Online (Sandbox Code Playgroud)