help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] "local" modifies the behavior of "$?"


From: Dan Douglas
Subject: Re: [Help-bash] "local" modifies the behavior of "$?"
Date: Sun, 23 Jun 2013 22:39:28 -0500

On Sunday, June 23, 2013, Peng Yu <address@hidden> wrote:
> Hi,
>
> The following code the difference between an local variable assignment
> and non local variable assignment wrt to "$?". Is this documented?
> Should the result be consistent between the two scenarios? Thanks.
>
> ~/linux/test/bash/man/shell_grammar/simple_commands/=$ cat main1.sh
> #!/usr/bin/env bash
>
> function cmd {
> local str=$(readlink -f -e xxxx)
> echo $?
> }
> cmd
>
> str=$(readlink -f -e xxxx)
> echo $?
> readlink -f -e xxxx
> echo $?
>
> ~/linux/test/bash/man/shell_grammar/simple_commands/=$ ./main1.sh
> 0
> 1
> 1

Not documented but frequently asked. One gets you the exit status of the "local" built-in. If you want the status of the command substitution then localize the variable separately.

function {
   typeset x
   x=$(cmd)
   echo $?
}

I'd also suggest using POSIX function syntax combined with "local" because it's supported by e.g. dash. "function" keywords imply you're aiming for ksh compatibility, which is imo more portable, but can be difficult.
reply via email to

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