Skip to content

Instantly share code, notes, and snippets.

@gorenje
Created February 3, 2011 09:55
Show Gist options
  • Save gorenje/809292 to your computer and use it in GitHub Desktop.
Save gorenje/809292 to your computer and use it in GitHub Desktop.
cd-alias-add bash command
ALIAS_FILE_CDS=~/.bash_aliases_cd
function _funct_cd_alias_add
{
local name=$1
name=$(echo $name | sed s/^cd-//) # remove any leading cd- (we'll add that)
local varname=$(echo $name | sed s/-/_/g) # replace minus with underscore
shift
local directory=$* # can't do replace on $* value directly -- man bash for more
if [ "$directory" == "" ]; then
directory=$(pwd)
fi
directory="${directory// /\\ }" # replace all spaces with slash-space
# remove (comment out) any existing alias with the same name
local tmpfile="/tmp/alias-file-$$-${RANDOM}"
rm -f $tmpfile
cat $ALIAS_FILE_CDS | sed s"/^alias cd-${name}=/#alias cd-${name}=/"g | \
sed s"/^export CD_${varname}=/#export CD_${varname}=/"g > $tmpfile
if [ -s $tmpfile ]; then # if tmpfile is greater than zero size
chgrp staff $tmpfile # this is a Apple thing .. otherwise move complains about the group
mv -f $tmpfile $ALIAS_FILE_CDS
fi
rm -f $tmpfile
# add alias and create alias for the current shell
local cd_cmd="alias cd-$name=\"pushd $directory\""
local cd_exp="export CD_${varname}=${directory}/"
echo "export CD_${varname}=${directory}/" >> $ALIAS_FILE_CDS
echo "alias cd-$name=\"pushd $directory\" ## `date`" >> $ALIAS_FILE_CDS
eval $cd_cmd
eval $cd_exp
}
alias cd-alias-add=_funct_cd_alias_add
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment