Skip to content

Instantly share code, notes, and snippets.

@refo
Last active February 2, 2024 11:57
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save refo/ed5da1ab621f535e04971987d507ce82 to your computer and use it in GitHub Desktop.
Save refo/ed5da1ab621f535e04971987d507ce82 to your computer and use it in GitHub Desktop.
Extract file name / file path parts using bash

Extract given file path into its parts

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

Example code to test the output

echo "Path:      $path"
echo "Dirname:   $dirname"
echo "Fullname:  $fullname"
echo "Basename:  $basename"
echo "Extension: $extension"

Output examples for the code above

$ ./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

Full script also checks if file exists

#!/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"
@jctourtellotte
Copy link

Thank you for posting this! It was very helpful to see this all in one place presented so concisely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment