Friday, March 15, 2013

Fizz Buzz in Bash

Fizz Buzz is a programming question given at interviews. Despite its absurd easiness it eliminates a large number of candidates. #!/bin/bash for i in {1..100}; do if [[ $(($i % 3)) -eq 0 && $(($i % 5)) -eq 0 ]]; then echo "fizz-buzz" elif [[ $(($i % 3)) -eq 0 ]]; then echo "fizz" elif [[ $(($i % 5)) -eq 0 ]]; then echo "buzz" else echo $i fi done But... This is more elegant #!/bin/bash for i in {1..100}; do if [[ $(($i % 15)) -eq 0 ]]; then echo "fizz-buzz" elif [[ $(($i % 3)) -eq 0 ]]; then echo "fizz" elif [[ $(($i % 5)) -eq 0 ]]; then echo "buzz" else echo $i fi done

chmod a-x /usr/bin/chmod

chmod a-x /usr/bin/chmod

This is a neat experiment I came across a while ago. It's useful as one of those "pull someone out of the fire" situations that you keep in your back pocket for when someone comes running asking for help.

Most users know chmod. Anyone who has used chmod would recognize the kind of situation chmod a-x /usr/bin/chmod puts your in. It's akin to burning a bridge behind you. It's a catch 22. You are changing the mode (specifically you are removing the execute permission) for the utility that changes file modes. After performing the change you would be left unable to change chmod back - its executable permission is gone!

# chmod a-x chmod
# chmod
-bash: /bin/chmod: Permission denied

What do you do?


Well, there are a few things, actually. First you could just invoke python or perl or some other language that has the ability to change file permissions. Second you could just re-install chmod. My first impulse when I originally saw this problem was "Just flip the mode bit" but that's not as elegant as it sounds.

My solution is to use tar. It's pretty safe to assume your distro has tar.

tar --mode 0777 -cf test.tar /usr/bin/chmod

tar -xvf test.tar

Will net you a free chmod with 777 permissions. # tar --mode 0777 -cf test.tar chmod # tar -xvf test.tar chmod # ls -la chmod -rwxrwxrwx. 1 root root 51248 Oct 5 2011 chmod