1753535 Members
8047 Online
108795 Solutions
New Discussion юеВ

Re: script ..

 
Dennis Handly
Acclaimed Contributor

Re: script ..

rm $(ls -ltr | awk 'NR <= 4 { print $9 }')

>Duncan: I can think of a good reason not to use for loops in this manner

Because 4 is too small to bother? :-)

Re: script ..

>Because 4 is too small to bother? :-)

no actually because what if the filenames are _really_ long (or we have a lot more than 4 files - not valid for this example but a generic reason to avoid for loops) - we can run into the problem of exceeding the max line length or argument count for the shell.

instead of:

for x in
do
...
done

I would always do:

cat | while read x
do
...
done

(syntactically incorrect, but you get the gist)
that lesson learnt after debugging a script which deleted archive logs in a directory - it stopped working when there we more than 255 logs present...

Duncan

I am an HPE Employee
Accept or Kudo
Dennis Handly
Acclaimed Contributor

Re: script ..

>Duncan: actually because what if the filenames are _really_ long (or we have a lot more than 4 files...) we can run into the problem of exceeding the max line length or argument count for the shell.

In both cases, you can't use a for-loop nor my $(). Typically 4 * N will always be less than 2 Mb.

>I would always do: while read x
>(syntactically incorrect

You mean evil cat incorrect. :-)

Yes, while read or xargs.