100 Useful Command-Line Utilities
by Oliver; 201447. dirname, basename
dirname and basename grab parts of a file path:$ basename /some/path/to/file.txt file.txt
$ dirname /some/path/to/file.txt /some/path/toThe first gets the file name, the second the directory in which the file resides. To say the same thing a different way, dirname gets the directory minus the file, while basename gets the file minus the directory.
You can play with these:
$ ls $( dirname $( which my_program ) )This would list the files wherever my_program lives.
In a bash script, it's sometimes useful to grab the directory where the script itself resides and store this path in a variable:
# get the directory in which your script itself resides
d=$( dirname $( readlink -m $0 ) )