Skip to content

Instantly share code, notes, and snippets.

@mokanfar
Last active December 12, 2022 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokanfar/b17ea36cdcc6d2f8743f4c58b907ba20 to your computer and use it in GitHub Desktop.
Save mokanfar/b17ea36cdcc6d2f8743f4c58b907ba20 to your computer and use it in GitHub Desktop.
Get the most recent file path (newest, last modified file) from a list of directories specified by user
#!/usr/bin/env bash
# Define an array of directories to search
dirs=("/Users/dan/Downloads" "/Users/dan/Desktop" "/Users/dan/Documents")
# Define an empty array to store the recent files
recent_files=()
# Define a variable to store the highest timestamp
highscore=0
# Define a function to find the most recent file in a directory
find_most_recent() {
# Get the directory to search
dir=$1
# Find the most recent file in the directory
mrf=$(ls -t $dir | head -1)
# Get the timestamp of the most recent file
timestamp=$(stat -f "%m" "$dir/${mrf}")
# Add the directory, file, and timestamp to the array of recent files
recent_files[${#recent_files[@]}]="${dir} ${mrf} ${timestamp}"
}
# Iterate over the directories and find the most recent file in each one
for dir in "${dirs[@]}"; do
find_most_recent "$dir"
done
# Find the file with the highest timestamp
for recent_file in "${recent_files[@]}"; do
# Get the timestamp of the current file
num=$(awk '{print $3}' <<< "$recent_file")
# Update the highscore if the current file has a higher timestamp
if [[ $num -gt $highscore ]]; then
highscore=$num
fi
done
# Find the file with the highest timestamp and copy its path to the clipboard
for recent_file in "${recent_files[@]}"; do
if [[ "$recent_file" =~ $highscore ]]; then
# Get the path of the file with the highest timestamp
path=$(awk '{print $1"/"$2}' <<< "$recent_file")
if [ "$1" == "-e" ]; then
#If -e flag specified echo it out
echo "$path" | tr -d '\n'
else
# Copy the path to the clipboard
echo "$path" | tr -d '\n' | pbcopy
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment