Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting Variable to Oldest File in the Directory

Status
Not open for further replies.

spaceherpe61

Technical User
Feb 1, 2005
8
US
I am looking for some help on using a wildcard in a bash script. I am trying to find the oldest file in directory. When I run the script using [user@server /usr/utilities]$sh -x script.sh <directory> the script works fine. It sets the variable to the oldest file. However when I run the script like this [user@server /usr/utilities]$./script.sh <directory>
it never sets the variable which blows up my script. Here is how I am setting the variable.

cd $1
getoldestfile=`ls -lat *.TXT | grep ^- | tail -1 | head -1`
file=`echo $getoldestfile |cut -d " " -f 9`

Any help would greatly be appreciated.
 
Maybe you need a tr in there:

file=`echo $getoldestfile | tr -s ' ' ' ' |cut -d " " -f 9`


I want to be good, is that not enough?
 
It sounds like on the second occasion it is not being run by the same shell; perhaps you are in C shell or something?

Try adding a shebang line #!/usr/bin/sh to the first line of the script to force it to run under sh?

Assuming that it's unlikely for a directory to exist matching *.TXT, I would shorten it to:

Code:
cd $1
file=`ls -t *.TXT | tail -1`

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top