There are two useful commands when scripting operations that involve filenames and paths. The first of these is dirname: dirname can be used to return the directory portion of a path. The second is basename: basename can be used to output the file name portion of a path.
For our first example, let’s say that we have an output of /users/krypted, which we know to be the original short name of my user. To just see just that username, we could use basename to call it:
Basename can also be used to trim output. For example, let’s say there was a document called myresume.pdf in my home folder and we wanted to grab that without the file extension. We could run basename using the -s option, followed by the string at the end that we do not want to see to output of (the file extension:
basename -s .pdf /users/charlesedge/myresume.pdf
The dirname command is even more basic. It outputs the directory portion of the file’s path. For example, based on the same string, the following would tell you what directory the user is in:
A great example of when this gets more useful is keying off of currently active data. For example, if we’re scripting a make operation, we can use the which command to get an output that just contains the path to the make binary:
We can then wrap that for expansion and grab just the place that the active make binary is stored:
dirname `which make`
This allows us to key other operations off the path of an object. A couple of notable example of this is home or homeDirectory paths and then breaking up data coming into a script via a positional parameter (e.g. $1).
You can also use variables as well. Let’s say that
homedir=/users/krypted ; dirname $homedir
Finally, keep in mind that dirname is relative, so if you’re calling it for ~/ then you’ll see the output at that relative path.
krypted April 5th, 2017