Skip to content

Instantly share code, notes, and snippets.

@crowding
Created August 2, 2012 03:18
Show Gist options
  • Save crowding/3232948 to your computer and use it in GitHub Desktop.
Save crowding/3232948 to your computer and use it in GitHub Desktop.
bash arrays, removing one path component at a time

I had a problem with chmod not working. It seemed to be related to something in my path. I spent more time on this script to test removing individual path components than I would have done brute forcing it. And it didn't tell me the problem, as it was related to at least two path entries.

However, this script does demonstrate something or other about working with arrays in Bash. Mostly it demonstrates how awkward the exercise is.

#!/bin/bash
#I had a problem with chmod not working It seemed to be related to my
#path. I spent more time on this script to test removing individual
#path components than I would have done brute forcing it. And it
#dodn't tell me the problem, as it was related to two path entries.
#However, this script does demonstrate something or other about
#working with arrays in Bash. Mostly it demonstrates how awkward the
#exercise is.
CANONICAL_PATH="/Library/Frameworks/EPD64.framework/Versions/Current/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:~/android-sdk-macosx/tools:~/android-sdk-macosx/platform-tools:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/texbin:/usr/X11/bin"
IFS=":"
set -- $CANONICAL_PATH
NUMBER="$#"
unset IFS
unset PATH_COMPONENTS
#0 based arrays, but the "set" builten sets starting at $1 and the {..}
#operator is inclusive. WTF.
for i in $(eval echo {1..$#}); do
eval "PATH_COMPONENTS[$i]=\${$i}"
done
for i in $(eval echo {1..$NUMBER}); do
NEWPATH=( "${PATH_COMPONENTS[@]}" )
unset NEWPATH[$(( $i - 1 ))]
IFS=":"
echo ${PATH_COMPONENTS[$i]}
PATH="${NEWPATH[*]}"
unset IFS
rm -f testscript
cat >testscript <<EOF
#!/bin/bash
echo "hello, world"
EOF
chmod a+x testscript
ls -l testscript
done
PATH=${CANONICAL_PATH}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment