basename /users/charlesedgeBasename 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.pdfThe 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:
dirname /users/charlesedgeA 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:
which makeWe 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 $homedirFinally, 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