bug-bash
[Top][All Lists]
Advanced

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

Re: Sourcing a script renders getopts impotent (or is it just me?)


From: Mun
Subject: Re: Sourcing a script renders getopts impotent (or is it just me?)
Date: Fri, 17 Sep 2010 09:49:28 -0700
User-agent: Mutt/1.5.20 (2009-06-14)

Hi Dennis,

On Thu, Sep 16, 2010 at 05:18 PM PDT, Dennis Williamson wrote:
DW> Use return instead of exit when you have an error and you're sourcing
DW> the script. You can make it conditional.
DW> 
DW> Try setting OPTIND=1 to make your script work when it's sourced.
DW> Initialize your script's variables since they will be carried over
DW> between runs when you source the script.

That was in fact the problem.  Once I set OPTIND in the script, it
worked correctly :)

DW> #!/bin/bash
DW> invoked=$_   # needs to be first thing in the script

Setting 'invoked' is a great idea.

Thanks for the quick and very helpful reply!

Regards,

-- 
Mun

DW> OPTIND=1    # also remember to initialize your flags and other variables
DW> 
DW> . . .    # do some stuff
DW> 
DW> if some error condition
DW> then
DW>     if [[ $invoked != $0 ]]
DW>     then
DW>         return 1    # the script was sourced
DW>     else
DW>         exit 1    # the script was executed
DW>     fi
DW> fi
DW> 
DW> 
DW> 
DW> On Thu, Sep 16, 2010 at 4:06 PM, Mun <mjelists@gmail.com> wrote:
DW> > Hi,
DW> >
DW> > Platform : Red Hat Enterprise Linux v5.5
DW> > Bash     : GNU bash, version 4.1.0(1)-release (x86_64-unknown-linux-gnu)
DW> >
DW> > I have a script which uses getopts that I need to source in my
DW> > interactive shell.  The problem is that if I source it, getops behaves
DW> > as if no arguments were passed into the script.  Although, if I simply
DW> > run the script in a sub-process, getopts works correctly.
DW> >
DW> > As an experiment, I echo'd all args prior to the getopts statement in
DW> > the script, and when the script was sourced all args were correctly
DW> > displayed.  So I'm at a loss as to why getopts doesn't seem to work when
DW> > the script is sourced.
DW> >
DW> > On a side note, there is some error checking being done within the
DW> > script.  I would like the script execution to terminate but leave the
DW> > interactive shell running upon error detection (i.e., don't exit out of
DW> > the terminal sessioni).  Is there any way to accomplish that objective
DW> > in bash?
DW> >
DW> > Regards,
DW> >
DW> > --
DW> > Mun
DW> >
DW> >
DW> 




reply via email to

[Prev in Thread] Current Thread [Next in Thread]