我可以扩展命令添加我自己的别名吗?

Rod*_*aki 2 alias command

我创建了一些别名来处理nodejs项目,例如:

alias lsc="cat package.json | jq '.scripts'"
Run Code Online (Sandbox Code Playgroud)

列出文件scripts部分中的所有可用命令package.json

理想情况下,我想将它作为npm scriptsnpm something但是npm是我路径中现有的可执行程序运行。

是否可以扩展它以添加我自己的别名?

Kus*_*nda 6

免责声明:我知道什么对Node.js的或npm

使用覆盖npm命令的 shell 函数:

npm () {
    if [ "$1" = scripts ]; then
        jq '.scripts' package.json
    else
        command npm "$@"
    fi
}
Run Code Online (Sandbox Code Playgroud)

这个 shell 函数检测函数的第一个参数是否是字符串scripts。如果是,它会运行您的jq命令。如果不是,它将npm使用原始命令行参数调用真正的命令。

command实用程序确保不调用该函数(否则将创建无限递归)。

上面的代码可以放在你定义普通别名的任何地方。

如果npm 已经是一个 shell 函数,这将无法做正确的事情。


将此扩展到许多新的子命令,if- then-elif代码会很混乱。反而:

npm () {
    case $1 in
        scripts)  jq '.scripts' package.json ;;
        hummus)   hummus-command ;;
        cinnamon) spice-command ;;
        baubles)  stuff ;;
        *) command npm "$@"
    esac
}
Run Code Online (Sandbox Code Playgroud)

这将创造scriptshummuscinnamonbaubles这将要求其他命令的子命令。如果函数的第一个参数与任何自定义子命令都不匹配,npm则像以前一样调用真正的命令。

请注意,为现有 npm子命令添加替代项将覆盖npm. 如果您想从您自己的替代子命令中调用那个真正的子命令,请调用command npm "$@"(假设您没有调用shift来移出子命令名称,在这种情况下您想调用command npm sub-command "$@")。

每个新的子命令都可以访问函数的命令行参数,但您可能希望shift从列表中删除子命令的名称:

npm () {
    case $1 in
        scripts)  jq '.scripts' package.json ;;
        hummus)
            shift
            echo '"npm hummus" was called with these additional arguments:'
            printf '%s\n' "$@"
            ;;
        *) command npm "$@"
    esac
}
Run Code Online (Sandbox Code Playgroud)

最后一个函数运行的例子:

$ npm hummus "hello world" {1..3}
"npm hummus" was called with these additional arguments:
hello world
1
2
3
Run Code Online (Sandbox Code Playgroud)