是否有自动保存别名的命令行工具/脚本?例如
save-alias my-ip="curl ipecho.net/plain"
Run Code Online (Sandbox Code Playgroud)
这将定义一个别名,然后在 ~/.bashrc 或 ~/.zshrc 中添加/更新它
我正在考虑编写一个脚本来定义别名然后自动保存它。每次都必须手动向配置文件添加别名很烦人。但我想也许我会重新发明轮子,你们已经有了解决这个烦恼的办法。
它将新别名添加到 .aliases 文件中并立即加载它们。它不会追加重复项两次,因此如果您多次定义相同的别名,它将更新以前的版本,而不是用重复项向您的配置文件发送垃圾邮件。
ALIASES_FILE_PATH=$HOME/.aliases
function save-alias() {
ALIAS_NAME=`echo "$1" | grep -o ".*="`
# Deleting dublicate aliases
sed -i "/alias $ALIAS_NAME/d" $ALIASES_FILE_PATH
# Quoting command: my-alias=command -> my-alias="command"
QUOTED=`echo "$1"\" | sed "s/$ALIAS_NAME/$ALIAS_NAME\"/g"`
echo "alias $QUOTED" >> $ALIASES_FILE_PATH
# Loading aliases
source $ALIASES_FILE_PATH
}
Run Code Online (Sandbox Code Playgroud)
它将别名存储在配置文件本身(.zshrc 或 .bashrc)中,而不是使用单独的文件作为别名。它还仅将别名附加到配置文件中的指定位置,以便您可以根据需要将其他内容保留在别名下面。它将在“# END ALIASES”之前附加别名,因此请确保您拥有准确的字符串。因此,例如,您的配置文件将如下所示:
plugins=(git)
#and bla bla bla
# ALIASES
alias test-alias="echo I was added automatically"
# END ALIASES
# Yes you can have the bottom of the config file free.
# Because it will store aliases inside ALIASES block
source $ZSH/oh-my-zsh.sh
# and etc
Run Code Online (Sandbox Code Playgroud)
这是通过以下代码完成的:
CONFIG_PATH=$HOME/.zshrc
function save-alias() {
ALIAS_NAME=`echo "$1" | grep -o ".*="`
# Checking whether the alias name is empty.
# Otherwise sed command later will match and delete every alias in the file
if [[ -z "$ALIAS_NAME" ]]; then
echo 'USAGE: save-alias alias_name="command" ' 1>&2
echo ' save-alias hello="echo hello world" \n' 1>&2
echo "Wrong format. Exiting..." 1>&2
exit 1
fi
# Deleting dublicate aliases
sed -i "/alias $ALIAS_NAME/d" $CONFIG_PATH
# Quoting command: my-alias=command -> my-alias="command"
QUOTED=`echo "$1"\" | sed "s/$ALIAS_NAME/$ALIAS_NAME\"/g"`
# Appending the command to the config (before "# END ALIASES")
sed -i "/# END ALIASES/i alias $QUOTED" $CONFIG_PATH
#reloading config file.
source $CONFIG_PATH
# instead of reloading the whole config you might want to append
# to a new file as well, then source it and then rm new file
}
Run Code Online (Sandbox Code Playgroud)
echo "alias ${1}" >> $HOME/.bash_aliases
Run Code Online (Sandbox Code Playgroud)
使用上面的命令(表示为“save-alias”),以下命令将失败
save-alias test-alias="echo hello world"
Run Code Online (Sandbox Code Playgroud)
它将失败,因为引号将被删除,并且它将附加命令,如下所示
alias test-alias=echo hello world
Run Code Online (Sandbox Code Playgroud)
它将失败并出现以下错误:
bash: alias: hello: not found
bash: alias: world: not found
Run Code Online (Sandbox Code Playgroud)
解决方案是使用双引号:
save-alias test-alias='"echo hello world"'
Run Code Online (Sandbox Code Playgroud)
这有点烦人
如果您运行命令两次,您会发现相同的别名将被添加到配置文件中两次:
alias test-alias="echo hello world"
alias test-alias="oh no the config file is getting spammed"
Run Code Online (Sandbox Code Playgroud)