在用户exand键入的命令行上填写命令

时间:2017-11-07 11:28:54

标签: linux bash shell

我想编写一个bash脚本/函数,可以在命令行中插入一些字符串,就像用户输入的那样?

例如,定义一个函数魔术:

function magic() {
  echo "ls -a" > 'whatever output that would do the trick'
} 

然后在bash类型中:

prompt> magic 

预先输入并获取直接在命令行注入的结果,可以修改或使用Enter键运行:

prompt> ls -a

简单来说,这就像功能驱动的别名扩展。

任何人都知道如何实现这个目标?

2 个答案:

答案 0 :(得分:1)

在这里自动回答。经过更多的搜索和一些测试,我终于实现了这个"简单"脚本:

function magic {
if [ "$READLINE_LINE" = "magic" ]
then
    #Do magic
    READLINE_LINE="ls -al"
    READLINE_POINT=6
else
    #exec any other command
    $READLINE_LINE

    #For unknown reason : have to add manually the command in history
    history -s "$READLINE_LINE"

    # Clear buffer for next command
    READLINE_LINE=""
    READLINE_POINT=0
fi
}

# Bind Enter key to magic function
bind -x '"\C-M" : magic'

魔术!

答案 1 :(得分:0)

您可以尝试使用Bash的programmable completion功能来支持类似的内容:

prompt> magic<tab>

我认为您可以为magic编写一个制表符完成脚本,它将用其他内容替换命令行,即使典型的是添加更多单词而不更改插入符号左侧的文本。< / p>

相关问题