[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: script line not working as its supposed to, but why?



* Gian Uberto Lauri wrote on 2013-12-11 at 12:42 (+0100):

> Sharon Kimble writes:
>
> > I want to delete the 'menu-*' files if there are more than 7,
> > and the command is parsed when I have 'set -x' at the head of
> > the script but this line does nothing! It runs but doesn't
> > achieve anything.
>
> I would try with something like this:
>
> if [  `ls -1 menu-* | wc -l` -gt 7 ]
> then
>     ls -t menu-* | tail $((7-`ls | wc -l`)) | xargs rm
> fi
>
> The first test ensures that you have more than 7 files.
>
> Then you list the files in reverse asciibetical order (that is
> older last), then the expression
>
> $((7-`ls | wc -l`))
>
> does the magic to compute the option to pass to tail so that it
> shows the last (number of files - 7). And finally xargs feeds
> rm. You can use rm -v to see them being deleted :)

This is too complicated: too many subshells, too many pipelines.

  $ cd /dir/with/files && LC_ALL=C ls menu-* | head -n -7 | xargs -r rm

will do the job:

* cd ... and && ensure that the directory exists and if (and only
  if it does the pipeline will be executed.

* LC_ALL=C ls menu-* lists all relevant files, one file per line,
  in the correct ascending order after the shell had expanded the
  "*".

* head -n -7 lists all but the last 7 lines.

* xargs -r will only call rm if there is some input.

For testing purposes run the above line without |xargs... part.

Although bash(1) is very long and its learning curve a little bit
steep I do recommend reading it.  In the long term there is no
way avoiding that.  Beginners may first tend to [1] and later to
[2].  Also, [3] is quite interessting.

Regards,
Mathias

[1] http://tldp.org/LDP/Bash-Beginners-Guide/html/index.html
[2] http://tldp.org/LDP/abs/html/
[3] http://www.gnu.org/software/bash/manual/bashref.html


Reply to: