0

My script looks like this

strenggen ( ) { something; }

strengen 1 
strengen 2
strengen 3
strengen 4
strengen 5
etc..

Which adds a few files to the directory called strengen?string=1, strengen?string=2 etc. What I am trying to do is if I quit the script, and the run it again, I want it to find the last number than was run, whether it was 13, 14, 60000 or 140000. Since the file names are contain the last number, I thought I can look for the last modified file and copy that number (e.g find . -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f2- -d" " or something similar. If I sed that string I can get the number to start at, but I am not sure how I would ignore the other lines?

1
  • I can't tell if you've simplified this snippet for the sake of your question...but is there some reason you're not using a for loop? for i in {1..500}; do strengen $i; done
    – Wildcard
    Oct 11, 2015 at 1:12

1 Answer 1

1

The following command will put the number of the latest 'strengen' file in the variable $LATEST:

LATEST=$(/bin/ls -1t | grep `^strengen` | head -1 | sed -e 's/strengen.*=//')

I've used /bin/ls here rather than just ls, in order to eliminate any aliasing that might affect the output of ls -1 - ls is very commonly aliased.

Also note that the ls option i'm using is -1 (number one) not -l (letter l). This tells ls to list one file per line. The -t option tells ls to sort by time, most recent first.

Another alternative would be to put something like the following at the top of your strenggen() function:

[ -e "strengen?string=$1" ] && return

This will cause the function to return immediately without doing anything if the file already exists.

9
  • Nice, but the result was the opposite. I got the oldest edited file. Oct 10, 2015 at 22:32
  • It shouldn't have. check the man page for ls: -t sort by modification time, newest first. and it sorted as expected on my system. you need to use the -r option to reverse sorting to get oldest first.
    – cas
    Oct 10, 2015 at 22:35
  • @cas - you need ls -tr.
    – mikeserv
    Oct 10, 2015 at 22:36
  • @cas, weird mine says something similar too Sort by time modified (most recently modified first) before sorting the operands by lexicographical order. Oct 10, 2015 at 22:37
  • 2
    my purpose here is to teach the technique. optimisation comes a very distant second to understanding.
    – cas
    Oct 10, 2015 at 23:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .