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

时间:2014-04-12 17:02:54

标签: bash shell variables

bash脚本中的$ COMP_LINE变量是什么? Bash Reference Manual有以下说法。

  

$ COMP_LINE

     

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

我不明白当前的命令行'手段。

我试图挑选this script:以查看它如何设法拦截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

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

[ -n "$COMP_LINE" ] && return

在运行脚本的其余部分之前,我假设它是某种检查或测试,因为[]是bash测试命令的别名,但由于我无法读取它,所以我无法理解它应该测试什么。

1 个答案:

答案 0 :(得分:4)

在Bash中,如果您有文件myfile.txt,则可以使用nano myfi 标签对其进行修改。这会自动完成文件名以节省您的输入,将命令转换为nano myfile.txt。这称为文件名完成

但是,并非所有命令都接受文件名。您可能希望能够执行ssh myho 标签并将其完整至ssh myhostname.example.com

由于bash不可能在所有系统中为所有已知和未知命令维护此逻辑,因此它具有可编程完成

通过可编程完成,您可以定义要调用的shell函数,该函数将从.ssh/known_hosts获取所有主机名,并使它们可用作完成条目。

调用此函数时,它可以检查变量$COMP_LINE以查看它应该为其提供建议的命令行。如果您已设置complete -F myfunction ssh并输入ssh myho 标签,则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"
}