[PLUG] 'cd ~' at the end of bash scripts

Eric Wilhelm scratchcomputing at gmail.com
Wed Jan 30 21:57:24 UTC 2008


# from Rich Shepard
# on Wednesday 30 January 2008 11:21:

>> I'm a bit fuzzy on how scripts work if they don't have a sh-bang
>> (#!/path/to/interpreter), but isn't the trailing "cd" is
>> unnecessary.
>
>Rogan,
>
>   Good point. Most of my shell scripts have the sh-bang on the first
> line, but some don't (soffice.sh, for example). All explicitly return
> to ~/ without harm or foul.

I can't see why they should.  If it is 'source'd, then any `cd`s within 
the script would impact the calling shell (which may not be in ~ -- and 
thus it should be remembering the initial $PWD and trying to return to 
that -- though that may not exist by that point (lots of fun exercises 
for the reader there), but to keep it simple: 'source'd scripts should 
really just not cd at all.)

If it is not sourced, then the subprocess is just trying to `cd` 
immediately before termination.  This hides the exit code of (what 
would otherwise be) the last command from the caller and instead 
returns the exit code of `cd ~`.

So, if the script just does environment setup and then runs a command, 
this practice masks that command's exit code and is likely to bite 
someone doing e.g. "for i in *; do some_wrapper.sh $i || break; done".

AFAIK, whether it has a shebang has nothing to do with any of that.

--Eric
-- 
I arise in the morning torn between a desire to improve the world and a
desire to enjoy the world. This makes it hard to plan the day.
--E.B. White
---------------------------------------------------
    http://scratchcomputing.com
---------------------------------------------------



More information about the PLUG mailing list