Reputation: 2565
I am writting shell script.
I have following files:
2012-03-08_16-37-41
2012-03-08_16-37-43
2012-03-08_16-37-46
2012-03-08_16-37-55
Simple script:
#!/bin/bash
FILENAME= ????
echo $FILENAME
And FILENAME
value should be 2012-03-08_16-37-55
(last element of sorted file name list). Also, begin of file name should be 2012
.
How could I solve this problem?
Upvotes: 2
Views: 5746
Reputation: 15582
Without using any external commands: set 2012*; eval FILE=\$$#
. This is a perfectly safe use of eval
.
Upvotes: 0
Reputation: 14910
Don't parse ls output. Instead, use find:
#!/bin/sh
find . -name 2012* | sort | tail -1
To assign the result to a variable:
#!/bin/sh
filename=$(find . -name 2012* | sort | tail -1)
This also gives you access to all of the many options find has, including (not)following symlinks, recursion, only returning files (not directories), checking timestamps and so on.
Upvotes: 2
Reputation: 36259
f="";
for f in 2012* ;
do
# haha - don't do anything.
dummy=42
done;
echo "now do something with $f"
Upvotes: 0
Reputation: 46876
You can use either the ls
command to get files, or just use "file globbing" to expand wildcards.
#!/bin/sh
for filename in 2012*; do
echo "File (by globbing) is $filename"
done
ls 2012* | while read filename; do
echo "File (via ls) is $filename"
done
To get the last one, the easiest way may be to sort the ls
output:
filename=`ls -r 2012* | head -1`
But you can also just tail the glob, if you want to be messy.
for filename in 2012*; do
echo "File (by globbing) is $filename"
done | tail -1
Upvotes: 1