Paul L. Snyder on 1 Feb 2006 22:05:36 -0000


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

Re: [PLUG] Interactive rm


On Wed, 01 Feb 2006, Andrew Libby wrote:

> Michael C. Toren wrote:
[...] 
> >morgan wrote:
> >
> rm file1 file2
> rm file*
> rm file.???
> 
> My bet is that the first case, he'd not want interactive rm, but in the
> second and third
> he would.   Am I correct in my supposition that wild cards are expanded
> prior to
> invocation of the shell function?  That would make this desire
> impossible, wouldn't it?
> Anyone have any idea how we might expand this solution to accommodate
> non-wild card
> multi parameter invocations or rm?

Here's a completely different approach from argument counting, which
regards wildcards, not multiplicity as the problem.

Yes, the shell globs before function invocation.  The Z shell has a couple
of options that directly address this.  By default it prompts if there
is a wildcard in the rm command's arguments; this behavior can be
disabled by setting the option RM_STAR_SILENT.  You can additionally
have the shell wait ten seconds before letting you type "yes", to
make sure you stop and think.

However, if you don't want to start using zsh yet, we can trick bash
into doing something along these lines.  The key: the magic parameter
GLOBIGNORE.  We first have to subvert globbing, which we can do with
an alias:

  alias rm='SAVE_GLOBIGNORE="$GLOBIGNORE"; GLOBIGNORE="*"; rm_maybe'

Now we write a function to perform the test for a wildcard in the
unexpanded command-line:

  rm_maybe()
  {
      if [[ "$*" =~ "\*" ]]; then
        GLOBIGNORE=$SAVE_GLOBIGNORE
        /bin/rm -i $*
      else
        GLOBIGNORE=$SAVE_GLOBIGNORE
        /bin/rm $*
      fi
      unset SAVE_GLOBIGNORE
  }

And we give it a try:

  $ ls
  $ touch bar baz
  bar  baz
  $ rm bar *az
  /bin/rm: remove regular empty file `bar'? n
  /bin/rm: remove regular empty file `baz'? n
  $ rm bar baz
  $ ls

Consult your friendly neighborhood 'man bash' for details.  I did a
quick test, and the above seems to work as advertised.  Extensions are
left as an exercise for the reader.

pls



___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug