0

I need to write a script which would execute some executables in a directory according to the last modified date. The oldest should run first. How do I do it?

This is what I have done so far

for f in  ./jobqueue/*; #accessing the queue
do 
    chmod +x *  # giving executable permission for the files
    $f  # running the executables
done
  • This could easily be a huge security hole depending on your environment. But other than that, it looks like the code you have should work if the files are names using a sequential naming scheme, except that the chmod command should be chmod +x $f (again, security red flags here). What specifically is not working as you expect? – depquid Apr 25 '13 at 19:09
  • The files are executing, but i need them to execute in the above mentioned order. Which means the oldest should run first – DesirePRG Apr 25 '13 at 19:11
  • What determines the file names? What are the rules and constraints on file names? – depquid Apr 25 '13 at 19:24
  • there are no rules. It can be any name. They are complied c programs. – DesirePRG Apr 25 '13 at 19:27
2

Provided that your filenames don't contain spaces or tabs or newlines or ? or * or [ and that the directory doesn't contain subdirectories, you might try something like

for f in $(ls -tr ./jobqueue/) ; do

  chmod +x ./jobqueue/$f
  ./jobqueue/$f

done
  • "there are no rules. It can be any name." - OP I find it ironic that this is the accepted answer, even with all of the filename qualifications. – depquid Apr 26 '13 at 12:25
3

Shell globbings are expanded in lexical order by default. If you need a different sort order, you'll need a shell that supports specifying the order like zsh which is probably a good thing since you're already using zsh syntax there (by not quoting $f).

for f in  ./jobqueue/*(.NOm); do
  chmod +x $f
  $f
done

The (.NOm) part is zsh's globbing qualifiers. . for regular files only, N to expand to nothing if there's no matching file instead of reporting an error (as if the nullglob option was enabled), Om to order (uppercase for reverse order) on modification time.

With the GNU shell (bash) and with GNU ls, the equivalent would be:

eval "files=($(ls -drt --quoting-style=shell ./jobqueue/* 2> /dev/null))"
for f in "${files[@]}"
  [ -f "$f" ] && [ ! -L "$f" ] || continue
  chmod +x -- "$f"
  "$f"
done
  • what does the (NOm) mean – DesirePRG Apr 25 '13 at 19:33
  • : syntax error near unexpected token `(' – DesirePRG Apr 25 '13 at 19:35
  • @DesirePRG, you missed the part that said zsh. It is zsh syntax, so you need zsh to interpret that script. – Stéphane Chazelas Apr 25 '13 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.