linux - 创建永久别名 bash 命令

标签 linux bash sh alias

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

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

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

允许以这种格式输入:

permalias commandname=\"commandbody\"

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

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

alias permalias="echo alias $1=\"$2\" >> ~/.bashrc"

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

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

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

谢谢

最佳答案

试试这个:

#!/bin/bash
permalias()
{
  local alias_regex='[A-Za-z_0-9]*'
  if
    [[ $# = 1 && $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 中是否存在所述别名,然后替换它,如果它已经存在则失败。

关于linux - 创建永久别名 bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43318889/

相关文章:

c++ - Libxml2 xmlSetGenericErrorFunc 跨进程使用

linux - 旧的 pid 是否在任何时候被重用?

bash - AES128-CBC "bad magic number"和 "error reading input file"

bash - 在 shell 脚本中使用 mkfifo

linux - 删除文件中匹配一个字符串但不匹配另一个字符串的行 - SED,BASH?

windows - .bat 文件中的 Sed 等价物

c++ - 与 ‘operator<<’ 不匹配(可能是因为我的 c++/gcc 版本?)

bash - 激活 venv 时无法使用 pip

bash - 如何启动并运行 sh 格式化程序?

linux - 在 bash/shell 脚本中使用 sudo 运行服务