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

Re: strange bash behavior



David Guntner <david@guntner.com> writes:

> Darac Marjal grabbed a keyboard and wrote:
>> On Mon, Sep 02, 2013 at 08:06:17AM -0700, David Guntner wrote:
>>> Matej Kosik grabbed a keyboard and wrote:
>>>> Hello,
>>>>
>>>> This morning I have been puzzled by bash.
>>>> After typing the following command:
>>>>
>>>> 	for i in `seq 1 5`;do echo $i; test $i = 3 && break; done
>>>>
>>>> I see:
>>>>
>>>> 	1
>>>> 	2
>>>> 	3
>>>>
>>>> Which is OK.
>>>>
>>>> However, if the "break" command appears in a subshell:
>>>>
>>>> 	for i in `seq 1 5`;do echo $i; test $i = 3 && (break); done
>>>>
>>>> then the "break" command does not seem to have any effect
>>>>
>>>> 	1
>>>> 	2
>>>> 	3
>>>> 	4
>>>> 	5
>>>>
>>>> I am curious, is this something to be expected?
>>>
>>> What do you mean by "appears in a subshell?"
>> 
>> From "man 1 bash":
>> (list) list  is  executed in a subshell environment (see COMMAND EXECU‐
>>        TION ENVIRONMENT below).  Variable assignments and builtin  com‐
>>        mands  that  affect  the  shell's  environment  do not remain in
>>        effect after the command completes.  The return  status  is  the
>>        exit status of list.
>
> Ok, I'm still not following you.
>
> What, exactly, is it that you are doing at your keyboard, in order to
> run it in this "subshell?"  I'm assuming that in your main one you're
> just typing the expression and hitting enter.  So what are you doing
> when the second example fails?

Based on his post, he is putting 'break' in parentheses in the second
case.  This causes a new shell (the subshell) to be created, and the
break command to be executed in that subshell.  The subshell then exits.

This is exactly the behavior I would expect:  the break command isn't
being executed by the same shell as your for-loop.  The for-loop has no
way of knowing that the subshell executed a break command (note that the
break command is a shell built-in command -- it is interpreted and
executed by the shell itself, no new process is created for it).


Reply to: