This trick is a bit bash specific instead of a real shell trick. On most unix systems you’ll find the commands
dirname and
basename. These are rather useless when you have got bash. First we’ll look at dirname.
The manual page of dirname states:
dirname - strip non-directory suffix from file name. In bash this would be accomplished by parameter expansion:
$ I=/home/joffie/geekblok.txt; echo ${I%/*}
/home/joffie
The description from the man page of basename is:
strip directory and suffix from filenames. So for example:
$ basename /home/joffie/geekblok.txt
geekblok.txt
The same can be accomplished with:
$ I=/home/joffie/geekblok.txt; echo ${I##*/}
geekblok.txt
The suffix part of the basename command can be done in two steps. What the command basename does is strip something from both sides of the string. So stripping suffix
.txt from $I too:
$ I=/home/joffie/geekblok.txt; J=${I##*/}; echo ${J%.txt}
geekblok
Bash can also be used when searching and replacing. Take a look at:
$ I=/home/joffie/geekblok.txt; echo ${I/geek/cool}
coolblok.txt
More info can be found in the
parameter expansion section of the man page of bash.