[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: |
Dennis Williamson |
Subject: |
Re: Sourcing a script renders getopts impotent (or is it just me?) |
Date: |
Thu, 16 Sep 2010 19:18:25 -0500 |
Use return instead of exit when you have an error and you're sourcing
the script. You can make it conditional.
Try setting OPTIND=1 to make your script work when it's sourced.
Initialize your script's variables since they will be carried over
between runs when you source the script.
#!/bin/bash
invoked=$_ # needs to be first thing in the script
OPTIND=1 # also remember to initialize your flags and other variables
. . . # do some stuff
if some error condition
then
if [[ $invoked != $0 ]]
then
return 1 # the script was sourced
else
exit 1 # the script was executed
fi
fi
On Thu, Sep 16, 2010 at 4:06 PM, Mun <mjelists@gmail.com> wrote:
> Hi,
>
> Platform : Red Hat Enterprise Linux v5.5
> Bash : GNU bash, version 4.1.0(1)-release (x86_64-unknown-linux-gnu)
>
> I have a script which uses getopts that I need to source in my
> interactive shell. The problem is that if I source it, getops behaves
> as if no arguments were passed into the script. Although, if I simply
> run the script in a sub-process, getopts works correctly.
>
> As an experiment, I echo'd all args prior to the getopts statement in
> the script, and when the script was sourced all args were correctly
> displayed. So I'm at a loss as to why getopts doesn't seem to work when
> the script is sourced.
>
> On a side note, there is some error checking being done within the
> script. I would like the script execution to terminate but leave the
> interactive shell running upon error detection (i.e., don't exit out of
> the terminal sessioni). Is there any way to accomplish that objective
> in bash?
>
> Regards,
>
> --
> Mun
>
>