Assuming, file passed as a parameter
path=$1
following script will extract file path into parts
fullname="${path##*/}"
dirname="${path%/*}"
basename="${fullname%.*}"
extension="${fullname##*.}"
# If the file is in the same directory with the script,
# path likely will not include any directory separator.
if [ "$dirname" == "$path" ]; then
dirname="."
fi
# If the file has no extension, correct the variable accordingly.
if [ "$extension" == "$basename" ]; then
extension=""
fi
echo "Path: $path"
echo "Dirname: $dirname"
echo "Fullname: $fullname"
echo "Basename: $basename"
echo "Extension: $extension"
$ ./filename.sh 5847dd4394cc6.png
Path: 5847dd4394cc6.png
Dirname: .
Fullname: 5847dd4394cc6.png
Basename: 5847dd4394cc6
Extension: png
$ ./filename.sh ../images/5847dd4394cc6.png
Path: ../images/5847dd4394cc6.png
Dirname: ../images
Fullname: 5847dd4394cc6.png
Basename: 5847dd4394cc6
Extension: png
#!/usr/bin/env bash
# If no parameter supplied, exit with usage help
if [ -z "$1" ]; then
echo
echo " Usage: $0 /path/to/file"
echo
exit 1;
fi
# If the file supplied does not exists or cannot be readable
if [ ! -r "$1" ]; then
echo "file \"${1}\" not found or couldn't read"
exit 1;
fi
path=$1
fullname="${path##*/}"
dirname="${path%/*}"
basename="${fullname%.*}"
extension="${fullname##*.}"
# If the file is in the same directory with the script,
# path likely will not include any directory seperator.
if [ "$dirname" == "$path" ]; then
dirname="."
fi
# If the file has no extension, correct the variable accordingly.
if [ "$extension" == "$basename" ]; then
extension=""
fi
# Print parts
echo "Path: $path"
echo "Dirname: $dirname"
echo "Fullname: $fullname"
echo "Basename: $basename"
echo "Extension: $extension"
Thank you for posting this! It was very helpful to see this all in one place presented so concisely.