Skip to content

Instantly share code, notes, and snippets.

@jctourtellotte
Forked from refo/bash-filepath-parts.md
Created February 2, 2024 11:56
Show Gist options
  • Save jctourtellotte/fbb0c73d24ff4447a4d85b37a889c2a0 to your computer and use it in GitHub Desktop.
Save jctourtellotte/fbb0c73d24ff4447a4d85b37a889c2a0 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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment