bash变量$ COMP_LINE是什么,它有什么作用?

Tar*_*oys 0 variables bash shell

bash脚本中的$ COMP_LINE变量是什么?《Bash参考手册》有以下内容。

$ COMP_LINE

当前命令行。该变量仅在外壳函数和由可编程完成工具调用的外部命令中可用(请参见可编程完成)。

我不明白“当前命令行”的含义。

我试图将这个脚本分开看看它如何管理拦截bash命令。

hook() {
    echo "$@"
}

invoke_hook() {
    [ -n "$COMP_LINE" ] && return
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return
    local command=`history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g"`;
    hook "$command"
}

trap 'invoke_hook' DEBUG
Run Code Online (Sandbox Code Playgroud)

我在弄清楚以下行应该做什么时遇到麻烦。

[ -n "$COMP_LINE" ] && return
Run Code Online (Sandbox Code Playgroud)

在运行脚本的其余部分之前,我假设它已经过某种检查或测试,因为[]是bash测试命令的别名,但是由于我看不懂它,所以我无法弄清楚它应该测试什么。

tha*_*guy 5

在Bash中,如果有文件myfile.txt,则可以使用进行编辑nano myfiTab。这样会自动完成文件名以保存您的输入,将命令转换为nano myfile.txt。这称为文件名完成

但是,并非所有命令都接受文件名。您可能希望能够做到ssh myhoTab并完成ssh myhostname.example.com

由于bash不可能期望对所有系统中的所有已知和未知命令都维护此逻辑,因此它具有可编程的完成功能

使用可编程完成,您可以定义要调用的shell函数,该函数将从中获取所有主机名.ssh/known_hosts并将其用作完成项。

调用此函数时,它可以检查变量$COMP_LINE以查看应为其提供建议的命令行。如果您已经设置 complete -F myfunction ssh并输入ssh myhoTab,那么myfunction它将运行并将$COMP_LINE设置为ssh myho

您的代码段使用了此功能,以使拦截器忽略由于按Tab键而运行的命令。这是带有注释的:

# This is a debug hook which will run before every single command executed 
# by the shell. This includes the user's command, but also prompt commands, 
# completion handlers, signal handlers and others.
invoke_hook() {

    # If this command is run because of tab completion, ignore it
    [ -n "$COMP_LINE" ] && return

    # If the command is run to set up the prompt or window title, ignore it
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return

    # Get the last command from the shell history
    local command=`history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g"`;

    # Run the hook with that command
    hook "$command"
}
Run Code Online (Sandbox Code Playgroud)