Defjam121
8/14/2017 - 10:19 AM

Add aliases without having to edit a bash file directly.

Add aliases without having to edit a bash file directly.

# function set_alias
#
# looks for the alias passed through $1 and $2 in file $3, and deletes it if it
# does exist, then appends to $3.
#
# $1 the name of the alias 
# $2 the command for the alias
# $3 (optional) the directory to store the aliases, defaults to ~/.bash_aliases
set_alias() {
    alias_name=$1
    alias_command=$2    
    
    [ -z $3 ] && alias_dir=~/.bash_aliases || alias_dir=$3
        
    if [ ! -f $alias_dir ]; then
        touch $alias_dir
        echo "# Custom aliases." >> $alias_dir
    fi      

    # See if the alias already exists. If it does, delete it.
    sed -i "/$alias_name/d" "$alias_dir"

    # Append the alias to the end of the file
    sed -ie "\$a alias $1='$2'" "$alias_dir"

    # Set it for this bash instance also.
    alias "$alias_name=$alias_command"
}