Skip to content

Instantly share code, notes, and snippets.

@andkirby
Last active April 19, 2017 12:02
Show Gist options
  • Save andkirby/96dd2d2c06f71a49055241bbf4728b68 to your computer and use it in GitHub Desktop.
Save andkirby/96dd2d2c06f71a49055241bbf4728b68 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Find possible writable binary directory
set -o pipefail
set -o errexit
set -o nounset
#set -o xtrace
# Set magic variables for current file & dir
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
readonly __dir __file
init_user_home_bin() {
if [ ! -d "$(cd; pwd)/bin" ]; then
mkdir -p "$(cd; pwd)/bin"
fi
}
writable_bin_path() {
local path_delimiter IFS paths
path_delimiter=$(echo ${PATH} | grep -oE '[;:]' | head -1)
while IFS="${path_delimiter}" read -ra paths; do
for i in "${paths[@]}"; do
if echo "${i}" | grep -E '^(/usr/|'$(cd; pwd)')' | grep -vE '(composer|vendor)' > /dev/null && [[ "${i}" =~ \/bin$ ]]; then
if touch ${i}/test_touch 2> /dev/null; then
rm -rf ${i}/test_touch
echo ${i}
break
fi
fi
done
done <<< "$PATH"
}
init_user_home_bin
writable_bin_path
@andkirby
Copy link
Author

andkirby commented Apr 19, 2017

Test with and without SUDO:

$ sudo bash find-bin-dir.sh
/usr/bin

$ bash find-bin-dir.sh
/home/myuser/bin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment