I'm trying to write a script that will display the name of oldest file within the directory that the script is executed from.
This is what I have so far:
#!/bin/bash
for arg in $*
do
oldest=$1
if [[ $arg -ot $oldest ]]
then
oldest=$arg
fi
done
echo "Oldest file: $oldest"
I'm not sure how to increment to the next file to check if it is older
for example:
oldest=$2
oldest=$3
etc..
trying to run this script in the bash shell given the following args:
myScript `ls -a`
I get a result of:
Oldest File: .
for arg in $*
is buggy -- try it with arguments that contain whitespace or quoted wildcards to see why.for arg in "$@"
or justfor arg
(as default behavior is to iterate over"$@"
) is the correct alternative. Of course, all of those are assuming that you're iterating over command-line arguments, not files.for arg in *
, perhaps with a[ -d "$arg" ] && continue
just inside the loop to skip directories.