How to: Get absolute/relative file paths, filenames and extensions from a Bash script

I’ve been learning some Qt stuff today, and the resulting code requires pre-processing of header files to work correctly, which I thought I’d try to automate. As part of this, I needed to find out how to get at all the different elements of a file from a bash script, so I did some googling and got all the info I needed :)

The script itself isn’t particularly useful, but the component parts of how to get at paths, extensions, and plain filenames without extensions definitely is – check it out:

fileParts Shell Script

# Bash script to get filename details | 16-06-2011 | r3dux
# Usage: fileParts <extension-with-no-dot> i.e. fileParts cpp
 
# For each file with the given extension in the current directory...
for file in ./*.$1; do
 
	# If a file exists with a given extension...
	if [ -e "$file" ]; then
 
		fullPath=$(readlink -f "$file")
		echo "Full path and filename          is: " $fullPath
 
		echo "Relative path and filename      is: " $file
 
		fileWithoutPath=$(basename $file)
		echo "Filename only                   is: " $fileWithoutPath
 
		extension=${fileWithoutPath##*.}
		echo "File extension only             is: " $extension
 
		fileWithoutExtension=${fileWithoutPath%.*}
		echo "Filename only without extension is: " $fileWithoutExtension
 
		echo
	else
		echo "No files of type $1 found!"
		exit 0
 
	fi # End of if file exists condition				
 
done # End of for each file loop

I created two dummy “.h” files in my home folder and ran the script – this is what it outputs:

r3d2@r3dux-Aspire-8920:~$ ./fileParts h
Full path and filename          is:  /home/r3d2/a-simple-test-file.h
Relative path and filename      is:  ./a-simple-test-file.h
Filename only                   is:  a-simple-test-file.h
File extension only             is:  h
Filename only without extension is:  a-simple-test-file
 
Full path and filename          is:  /home/r3d2/file.with.lots.of.dots.h
Relative path and filename      is:  ./file.with.lots.of.dots.h
Filename only                   is:  file.with.lots.of.dots.h
File extension only             is:  h
Filename only without extension is:  file.with.lots.of.dots

That’s gotta come in useful, right? =D

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.