Bash Cheat Sheet - File operation

Get filename with file extension

FULLFILENAME=$(basename $FILE)

Get filename without file extension

FILENAME="${FILE%.*}"

Get extension from filename

EXTENSION="${FILE##*.}"

Get MIME type of the given file

MIME_TYPE="$(file --brief --mime-type "$FILE")"

Get current directory of the script

Get the full directory name of the script no matter where it is being called from. Uses Bash variable BASH_SOURCE. reference source

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Get the name of the script

Simple way to get the script name

PROGRAMNAME=${0##*/}

Advanced method to get the script name. The below code will also try to resolve symbolic link.

PROGRAMNAME="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"
PROGRAMNAME=${PROGRAMNAME%.*}

Get the directory path for a given filepath

The below code will resolve relative path or symlink into absolute directory path for a given filepath.

DIR="$(dirname "$(readlink -f $FILE)")"

Preserve file timestamp from original file

filemodtime=$(stat -c%y "$FILE" | sed 's/[ ]\+/ /g')
touch -m -d "$filemodtime" "$NEWFILE"

Find and update access time

Find all files in folder and update the access time to specified time.

find /var/files/ -type f -atime +1 -exec touch -a --date="2016-03-10" {} \;

Changing a File "Access" and "Modification" Time

Change a file's access time (atime) :
touch -a --date="2016-03-10" file.txt
touch -a --date="2016-03-10 02:00" file.txt
touch -a --date="2016-03-10 02:00:22.432346231 +0421" file.txt
Change a file's modification time (mtime) :
touch -m --date="2025-03-12" file.txt
touch -m --date="2025-03-12 21:04" file.txt
touch -m --date="2025-03-12 21:04:22.432346231 +0421" file.txt

Update All time of a file to specific time

The below command copies the current time to a variable. then update the system date to any specified time and then update the timestamp of the file and revert back system time to default.

NOW=$(date) && date -s "2030-08-15 21:30:11" && touch file.txt && date -s "$NOW" && unset NOW

Remove Whitespace from File names

This command will find all the files from the directory where the command is run and removes spaces in file names.

find $1 -name "* *" -type f -print0 |   while read -d $'\0' f; do mv -fv "$f" "${f// /}"; done

Reference