Reputation:
I know the command touch file_example
to set the file file_example
to the newest modified file (which appears at the bottom when I do a ls -lrt
).
Now, I would like to execute a short command to set the file file_example
to the oldest file in a given directory, i.e which appears on first line when I do a ls -lrt
.
Is it possible to make it with a quick command ?
Upvotes: 0
Views: 189
Reputation: 52112
You can loop over all files, and whenever you find one that's older than file_example
, you can update file_example
:
for f in ./*; do
# Skip directories
[[ -d $f ]] && continue
# Compare and update
[[ $f -ot file_example ]] && touch file_example -r "$f"
done
If you want to include hidden files, you can either loop with for f in ./* ./.*
, or use shopt -s dotglob
first.
This can be packaged in a shell function:
settooldest() {
local file=$1
local dir=$2
local f
for f in "$dir"/*; do
[[ -d $f ]] && continue
[[ $f -ot $file ]] && touch "$file" -r "$f"
done
}
Which is called like
settooldest file_example path/to/dir
Upvotes: 1