Skip to content

Instantly share code, notes, and snippets.

@simonLeary42
Created June 18, 2023 18:33
Show Gist options
  • Save simonLeary42/2a69750c15a9bd2fa93cc8f4ec0c3ae7 to your computer and use it in GitHub Desktop.
Save simonLeary42/2a69750c15a9bd2fa93cc8f4ec0c3ae7 to your computer and use it in GitHub Desktop.
#!/bin/sh
prepend_path() {
if [ -z "$1" ] || [ -z "$2" ]; then
echo "usage: prepend_path <directory> <env.var>"
echo "e.g. prepend_path ~/.local/bin PATH"
echo "received: prepend_path $@"
return 1
fi
local dir="$1"
local env_var="$2"
if [ ! -d "$dir" ]; then
echo "\"$dir\" cannot be prepended to \"$env_var\" because it is not a directory."
return 1
fi
# Remove directory if it already exists in the variable
if eval "echo \$$env_var | tr ':' '\\n' | grep -xqF \"$dir\""; then
echo "\"$dir\" already present in \"\$$env_var\", moving to front..."
# colon2newline, reove $dir, remove trailing newline, then newline2colon
eval "export \$env_var=\$(echo \"\$$env_var\" | tr ':' '\\n' | grep -vxF \"$dir\" | sed -Ez 's/\n+$//' | tr '\\n' ':')"
fi
if eval "[ -z \"\$$env_var\" ]"; then
cmd="export $env_var=\"$dir\""
else
cmd="export $env_var=\"$dir:\$$env_var\""
fi
eval $cmd
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment