I seem to have failed at something pretty simple, in bash. I have a string variable that holds the full path to a directory. I’d like to assign the last two directories in it to another string. For example, if I have:
DIRNAME = /a/b/c/d/e
I’d like:
DIRNAME2 = d/e
I’m sure there’s a simple bash construct or sed command that will do it, but it’s escaping me. I’d sort of like a generalized version of basename or dirname that doesn’t just return the extreme parts of a name.
Thanks!
Or, in one line (but be careful with all the double quotes — it is easier when it is split up):
Don’t try that game with back-quotes unless you’re heavily into masochism. And if there might be spaces in the paths, use double quotes around the variable names.
This will work with almost any shell Korn Shell as well as Bash. In
bash, there are other mechanisms available – other answers illustrate some of the many options, thoughexpris also an old-school solution (it was present in 7th Edition Unix too). This code using back-quotes works in Bash and Korn shell too — but not in Heirloom Shell (which is similar to a Unix System V Release 2/3/4 shell, IIRC).(Two levels of nesting is not too awful, but it is pretty bad; three gets really tricky!)
Testing
When testing path name manipulation that should survive spaces in the path name, it is worth testing with a name containing double-spaces (rather than, or as well as, single spaces). For example:
The output from that is: