Skip to content

Instantly share code, notes, and snippets.

@samthor
Created June 6, 2019 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samthor/23d5f0a6e3a94c2f05310a197299a78d to your computer and use it in GitHub Desktop.
Save samthor/23d5f0a6e3a94c2f05310a197299a78d to your computer and use it in GitHub Desktop.
#!/bin/bash
# Useful bash functions. This is sourced by the environment file.
# These are available to scripts, but you shouldn't use them in scripts if you
# want them to be portable.
# Usage: pathremove /path/to/bin [PATH]
# Eg, to remove ~/bin from $PATH
# pathremove ~/bin PATH
function pathremove {
local IFS=':'
local NEWPATH
local DIR
local PATHVARIABLE=${2:-PATH}
for DIR in ${!PATHVARIABLE} ; do
if [ "${DIR}" != "${1}" ] ; then
NEWPATH="${NEWPATH:+${NEWPATH}:}${DIR}"
fi
done
export ${PATHVARIABLE}="${NEWPATH}"
}
# Usage: pathprepend /path/to/bin [PATH]
# Eg, to prepend ~/bin to $PATH
# pathprepend ~/bin PATH
function pathprepend {
pathremove "${1}" "${2}"
[ -d "${1}" ] || return
local PATHVARIABLE="${2:-PATH}"
export ${PATHVARIABLE}="${1}${!PATHVARIABLE:+:${!PATHVARIABLE}}"
}
# Usage: pathappend /path/to/bin [PATH]
# Eg, to append ~/bin to $PATH
# pathappend ~/bin PATH
function pathappend {
pathremove "${1}" "${2}"
[ -d "${1}" ] || return
local PATHVARIABLE=${2:-PATH}
export $PATHVARIABLE="${!PATHVARIABLE:+${!PATHVARIABLE}:}${1}"
}
# Usage: ssource /path/to/shellscript
# Checks if the file exists before sourcing it
function ssource {
[ -r "${1}" ] && source "${1}"
}
# Usage: mcd somedir
# Creates the directory if it doesn't exist, and changes into it
function mcd {
mkdir -p "${1}" &&
cd "${1}"
}
# Include any local functions from a standard local path.
ssource "${HOME}/.local/env/functions-local"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment