Monday, November 29, 2010

Just getting the current directory from command line

A request from a co-worker turned out to be more complicated than I though. He just wanted the current root directory, not the full path, to be returned.

Turns out BASH doesn't provide this functionality directly to you, but does provide tools to enable your own solution. We'll use PWD to nab the full directory path, and then find a way to extract the last returned directory. So the cast:
  • PWD - returns the working directory name in a full path
  • CUT - cut's out selected protions of each line in a file
  • python - to reveres a string. You can switch this element out with ruby or any other preferred method.
The Command:

pwd | python -c "print raw_input()[::-1]" | cut -d'/' -f 1 | python -c "print raw_input()[::-1]"

Under the Hood:
PWD prints out the full path. Then we use Python to reverse the string. Putting our last directory first. Next we use CUT to define the path as a list. Where the delimiter breaks it down into separate fields by '/'. We then specify we want the first field returned, which is secretly the last directory that has been reversed. Finally we re-reverse the returned string back to it's original state.
  1. pwd: /Users/tspangle/Documents/projects
  2. python: stcejorp/stnemucoD/elgnapst/sresU/
  3. cut: stcejorp
  4. python: projects









No comments:

Post a Comment