Skip to content

Instantly share code, notes, and snippets.

@Error601
Last active April 7, 2016 20:44
Show Gist options
  • Save Error601/ca652c92d3b8919c5f81a9e7d1f0d7e8 to your computer and use it in GitHub Desktop.
Save Error601/ca652c92d3b8919c5f81a9e7d1f0d7e8 to your computer and use it in GitHub Desktop.
Setup a folder to contain individual alias files that can be easily created.
#!/bin/bash
[[ ! -d ~/.bash_alias ]] && mkdir -p ~/.bash_alias
# path to individual alias files
APATH=~/.bash_alias
ALIASPATH=$APATH
AFILES=($APATH/*.sh)
ALIASFILES=$AFILES
# add alias files from ~/.bash_alias
if [ -e ${AFILES[0]} ];then
for AFILE in $AFILES; do
source $AFILE
done
fi
# isalias 'foo'
isalias() {
if [ -e $APATH/$1.sh ]; then
echo "Alias exists.";
return 0;
else
echo "Alias does not exist.";
return 1;
fi
}
# command to EASILY add, replace, or append a new alias
# addalias "foo='ls'"
addalias() {
# extract alias name
aliasname=${1%=*}
isalias $aliasname
yesitis=$?
addit=yes
addto=no
yn=N
aliasfile=$APATH/$aliasname.sh
# what happens if the alias file exists?
if [[ $yesitis == 0 ]]; then
read -p "Would you like to overwrite it? [y/N] " yn
if [[ $yn =~ [Yy] ]]; then
addit=yes
else
read -p "Would you like to append to the existing alias file '${aliasname}.sh'? [y/N] " yn
if [[ $yn =~ [Yy] ]]; then
addit=no
addto=yes
else
echo "Choose a different name."
addit=no
addto=no
return 1;
fi
fi
fi
if [[ $addit == yes ]]; then
echo "Creating alias file '${aliasname}.sh' in '${APATH}/'"
echo "alias ${1}" > $aliasfile && echo "Alias created." || echo "An error occurred."
fi
if [[ $addto == yes ]]; then
echo "Appending to alias file '${aliasname}.sh' in '${APATH}/'"
echo "# appended $(date)" >> $aliasfile
echo "alias ${1}" >> $aliasfile && echo "Alias updated." || echo "An error occurred."
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment