Skip to content

Instantly share code, notes, and snippets.

@shawngmc
Last active November 16, 2024 17:26
Show Gist options
  • Save shawngmc/954ef4ccee03a26f1774c5b922e27777 to your computer and use it in GitHub Desktop.
Save shawngmc/954ef4ccee03a26f1774c5b922e27777 to your computer and use it in GitHub Desktop.
Bash helper: Add Path
#!/bin/bash
# Based on: https://dev.to/christianpaez/simplifying-path-management-with-bash-4870
# Install via:
# sudo curl -o /usr/bin/add-path -L https://gist.githubusercontent.com/shawngmc/954ef4ccee03a26f1774c5b922e27777/raw/add-path
# sudo chmod 755 /usr/bin/add-path
unset dir_to_add
unset force_add
unset do_add
usage() {
echo "Usage: ${0} [-f] [-p <path>|-c]" 1>&2;
echo " -c : Add current path" 1>&2;
echo " -p <path> : Add specified path" 1>&2;
echo " -f : Force add, even if in current PATH" 1>&2;
exit 1;
}
# Function to add current directory to PATH in .bashrc file
add_dir_to_path() {
local shell_config=".bashrc"
local do_add=false
# Check if the directory is already in PATH
if [[ ":${PATH}:" == *":${dir_to_add}:"* ]]; then
echo "${dir_to_add} is already in PATH."
if [ -z ${force_add} ]; then
echo "Do you wish to add ${dir_to_add} to .bashrc anyway?"
select yn in "Yes" "No"; do
case ${yn} in
Yes ) do_add=true; break;;
No ) exit;;
esac
done
else
do_add=true
fi
else
do_add=true
fi
if [[ "${do_add}" == true ]]; then
# Append the current directory to the PATH variable
echo "export PATH=\$PATH:${dir_to_add}" >> "${HOME}/${shell_config}"
echo "${dir_to_add} added to PATH in ${shell_config}."
echo "Remember to execute 'source ${shell_config}' to update the PATH."
fi
}
while getopts ":p:hcf" o; do
case "${o}" in
c)
echo "Using current directory: $(pwd)"
export dir_to_add=$(pwd)
;;
p)
export dir_to_add=${OPTARG}
;;
f)
export force_add=true
;;
h)
usage
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
echo "${dir_to_add}"
if [ -z "${dir_to_add}" ]; then
usage
else
add_dir_to_path
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment