创建永久别名 bash 命令

Creating permanent-alias bash command

我正在尝试创建一个 "permalias" bash 命令,以便能够轻松创建永久别名,而无需直接处理 ~/.bashrc 文件。

到目前为止,我能够完成这项工作的唯一方法是使用以下代码:

alias permalias="echo alias  >> ~/.bashrc"

允许以这种格式输入:

permalias commandname=\"commandbody\"

但我对此并不满意,因为我想保留一种更简单的输入格式,更接近于原始别名命令的输入格式。

我尝试了这段代码的几种变体:

alias permalias="echo alias =\"\" >> ~/.bashrc"

使用此版本,此代码 permalias c "echo test" 应将此行 alias permalias c="echo test" 添加到 ~/.bashrc 文件。

但结果是这样的:alias c "echo test",这当然行不通。

对于如何避免将 " 放在新命令主体周围的需要的任何建议,我也将不胜感激。

谢谢

您不能在 alias 中使用参数。你需要的是一个函数,比如:

permalias() {
    echo "alias =\"\"" >> ~/.bashrc
}

按照 Olli 的说法让它成为一个函数,然后你可以使用 "$*" 将所有参数连接到函数。

permalias() { 
    n=; 
    shift; 
    echo "alias $n=\"$*\"" >> ~/.bashrc; 
}

这应该适用于像 permalias c echo foo bar 这样的东西,但如果你真的想要引号 别名中,它会变得毛茸茸。 permalias c echo "foo bar" 行不通,您需要 permalias c echo "'foo bar'" 之类的东西来应对额外级别的命令行处理并获取文件的内部引号。

对于任何复杂的东西,最好还是制作一个 shell 函数。您可以使用 declare -fp funcname 打印函数的定义,并根据需要将其保存到文件中。

试试这个:

#!/bin/bash
permalias()
{
  local alias_regex='[A-Za-z_0-9]*'
  if
    [[ $# = 1 &&  =~ ($alias_regex)=(.*) ]]
  then
    printf "%s\n" "${BASH_REMATCH[1]}=\"${BASH_REMATCH[2]}\"" >> ~/.bashrc
  else
    echo "USAGE: permalias VARNAME=ALIAS_COMMAND"
    return 1
  fi
}

更好的版本会首先检查 .bashrc 中是否存在所述别名,然后替换它,如果它已经存在则失败。

如果你碰巧使用 zsh,借鉴 Fred 的 ,我们可以将 $BASH-REMATCH 切换为 $match 并将别名发送到 .zsh_aliases(假设你有他们设置 - 如果没有添加 .zsh_aliases 到你的 homedir 并将其添加到你的 .zshrc: source ~/.zsh_aliases).

因此,作为示例,我将此函数添加到我的 .zsh_aliases 文件中,并且运行良好。

 permalias() {
    sauce="unhash -ma "*" ; unhash -mf "*"; source ~/.zshrc"
    local alias_regex='[A-Za-z_0-9]*'
    if
        [[ $# == 1 &&  =~ ($alias_regex)=(.*) ]]
    then
        printf "%s\n" "alias ${match[1]}=\"${match[2]}\"" >>~/.zsh_aliases
        #uncomment the following line to automatically load your new alias
        #eval ${sauce}
    else
        echo "Usage: permalias ALIAS_NAME=ALIAS_COMMAND"
        return 1
    fi
}