Ages ago I made a small bash
script which would add a command cdp
, standing for "change directory - project".
What it did was simple, it added all folders in ~/projects
as autocompletion and CD'd me into them using only the project folder's name.
Over time I switched to a different company where I started working with Python, thus needing virtual environments not to mess up my workstation, which led me to adding more functionalities to the script.
I rarely use bash to do anything, rather using Python or even PHP for simple CLI tasks. I was hoping for some input regarding my first ever bash script, though, so I can keep my terminal scripts in its native language.
I think some improvements could be the way I name and call functions, and the newly added command should probably be something other than an alias.
#!/usr/bin/env bash
funcCheckVirtualEnvironment()
{
if [ -d "venv/" ]; then
read -p "A virtual environment was found for this project, would you like to execute the activation script? [y/n]" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
source venv/bin/activate
if [ -e "requirements.txt" ]; then
read -p "PyPi requirements were found, would you like to install any uninstalled packages? [y/n]" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
pip install -r requirements.txt
fi
fi
fi
fi
}
funcCDP()
{
# Add more flags in future, maybe
case "$1" in
"-r" )
funcCheckVirtualEnvironment
return 0 ;;
esac
if [ -d ~/projects/$1 ]; then
cd ~/projects/$1;
funcCheckVirtualEnvironment
else
echo "Directory $1 does not exist!"
fi
}
funcCD()
{
if [ $1 == "-"] || [ -d $1 ]; then
command cd "$@"
if [ -d "venv/" ]; then
funcCheckVirtualEnvironment
fi
else
echo "No such file or directory: $1"
fi
}
_cdp()
{
local cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -W '$(\ls ~/projects)' -- $cur) )
}
complete -F _cdp cdp
alias cdp=funcCDP
alias cd=funcCD
virtualenvwrapper
for python? It has an awesome featuresetvirtualenvproject
which binds any project/directory to an existing/active virtualenv; and later you cancdproject
to switch to that. \$\endgroup\$virtualenvwrapper
is a friendlier (read humane) version forvirtualenv
. \$\endgroup\$