Improve function that adds aliases to .bashrc from command line

332 views Asked by At

I wrote this function which I use to add aliases to .bashrc file. The function works well but it's not complete, I would like to ask for confirmation from the user if the alias being added already exists and write the if condition in order to achieve the "modified" part of the code if confirmation is given, just like when you install a new package.

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'
2

There are 2 answers

0
Alan On BEST ANSWER

I'm adding an answer for future reference, credits to @4ae1e1 and @ArunSangal. Their suggestions are in the comments.

# 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"
0
cspoleta On

This function adds an alias to both the current shell and to ~/.bash_aliases at the same time. I always test the alias manually before submitting it to add-alias. It works well for me and I have been using it for a long time. Of course I don't run a production system.

YMMV.

add-alias ()  
{  
local name=$1 value="$2"  
echo alias $name=\'$value\' >> ~/.bash_aliases  
eval alias $name=\'$value\'  
alias $name  
}  

You can add the bells & whistles.