Last active
March 31, 2017 14:26
-
-
Save farsil/8a03869919779e8c468b72f558b121f5 to your computer and use it in GitHub Desktop.
POSIX-compliant function to prepend a path to an environment variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# | |
# Usage: pushv VAR PATH | |
# | |
# Prepends PATH to the VAR variable. VAR should be a variable name, the | |
# variable itself should contain a colon-separated list of paths. The function | |
# sets VAR if previously unset and marks it for exporting. This function does | |
# nothing if PATH does not exists or if it is already present in VAR. | |
# | |
# EXAMPLE | |
# | |
# $ echo $PATH | |
# /usr/bin:/bin | |
# $ push PATH /usr/local/bin | |
# $ echo $PATH | |
# /usr/local/bin:/usr/bin:/bin | |
# $ push PATH /usr/local/bin | |
# $ echo $PATH | |
# /usr/local/bin:/usr/bin:/bin | |
# | |
# It is definitely a ugly hack, but what in the shell scripting world isn't :) | |
pushv() { | |
# Don't bother if PATH does not exist | |
if [ -d "$2" ]; then | |
# Appends the content of VAR to the argument array. Ugly, but | |
# in POSIX there is no local, and this keeps the namespace clean. | |
eval set -- "$1 $2 \$$1" | |
# If the variable is empty, just set it | |
if [ -z "$3" ]; then | |
eval "export $1=$2" | |
else | |
case ":$3:" in | |
# If PATH already exists in VAR do nothing | |
*":$2:"*) ;; | |
*) eval "export $1=$2:$3" ;; | |
esac | |
fi | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment