我编写了这个函数,我用它来为.bashrc文件添加别名。 该功能运行良好但不完整,我想请求用户确认添加的别名是否已经存在并写入if条件以实现"修改"部分代码,如果给出确认,就像安装新软件包一样。
add_alias(){
d_alias=$1
d_command="$2"
replacing=alias|grep "alias $d_alias"
if [[ "$replacing" -ne 0 ]];
then
sed -i "/alias $d_alias/d" $HOME/.bashrc
echo "alias $d_alias modified in ~/.bashrc"
else
sed -i ':a;$!{N;ba};s,\(auto-generated code\),\1\nalias '"$d_alias"'='"'$d_command'"',2' $HOME/.bashrc
source ~/.bashrc
echo "alias $d_alias added to ~/.bashrc"
fi
}
#auto-generated code
alias brc='source ~/.bashrc'
alias client='/home/user/workspace/client'
alias workspace='/home/user/workspace'
答案 0 :(得分:1)
我添加了一个答案供将来参考,@ 4ae1e1和@ArunSangal。他们的建议在评论中。
# TODO Room to improve - add_alias()
# Add new aliases to this .bashrc file
#-------------------------------------
add_alias(){
n_alias=$1
shift
n_command="$@"
replacing=$( alias $n_alias 2>/dev/null|wc -l )
if [[ "$replacing" = "1" ]];
then
b $n_alias # cat|grep .bashrc in color
read -p "Do you wish to overwrite this(these) alias(es)? [y/n]" yn
case $yn in
[Yy]* ) sed -i '/alias '"$n_alias"'/d' $HOME/.bashrc;
sed -i ':a;$!{N;ba};s,\(auto-generated code\),\1\nalias '"$n_alias"'='"'$n_command'"',3' $HOME/.bashrc;
source ~/.bashrc;
echo "alias $n_alias modified in ~/.bashrc" ;;
[Nn]* ) echo "Operation canceled";;
* ) echo "Please answer yes or no.";;
esac
else
sed -i ':a;$!{N;ba};s,\(auto-generated code\),\1\nalias '"$n_alias"'='"'$n_command'"',3' $HOME/.bashrc
source ~/.bashrc
echo "alias $n_alias added to ~/.bashrc"
fi
}
alias aa='add_alias'
# end of add_alias()
# auto-generated code
alias cdn='ssh cdn'
alias cdn2='ssh cdn2'
alias sxdev64="ssh sxdev64"
alias csi="ssh csi"
alias malt="ssh malt"