Linux: How to get the basename from the full filename

As a quick note today, if you’re ever writing a Linux shell script and need to get the filename from a complete (canonical) directory/file path, you can use the Linux basename command like this:

$ basename /foo/bar/baz/foo.txt
foo.txt

Or, if you know the filename extension and want to get the first part of the filename — the base filename, the part before the extension — you can also use basename like this:

$ basename /foo/bar/baz/foo.txt  .txt
foo

I was just working on a little Unix shell script, and wrote this code to loop over a bunch of LaTeX files in the current directory:

for file in `ls -1 *.tex`
do
    baseFilename=`basename $file .tex`
    echo "creating ${baseFilename}.html ..."
    # my other commands here
done

If you’re ever working on a Linux system and need to get the “basename” from a complete filename, including the filename extension, I hope these examples help. See the basename man page for more information.