Re: [Help-bash] View Positional Parameters of Commands
From:
Clark Wang
Subject:
Re: [Help-bash] View Positional Parameters of Commands
Date:
Wed, 29 Jul 2015 09:31:10 +0800
On Wed, Jul 29, 2015 at 9:10 AM, Michael Convey <address@hidden> wrote:
> ββ
> On Tue, Jul 28, 2015 at 8:12 AM, Clark Wang <address@hidden> wrote:
>
>> For example:
>>
>
>> $ foo() { echo $0 $1 $2; }
>> $ foo
>> /Users/clarkw/utils/bin/bash
>> $ foo -a
>> /Users/clarkw/utils/bin/bash -a
>> $ foo -al
>>
>> ββ
>> /Users/clarkw/utils/bin/bash -al
>> $ foo -al bar
>>
>> ββ
>> /Users/clarkw/utils/bin/bash -al bar
>> $
>>
>
> ββExcellent example thank you. I'm still unclear why the output of your
> last command is,
>
> β
> β
> β
> /Users/clarkw/utils/bin/bash -al bar
> β
> βinstead of,
>
> foo β-al bar
> ?
>
$0 expands to the name of the shell or shell script. To get the current
function name in a function, use $FUNCNAME. E.g.:
$ foo() { echo $FUNCNAME; }
$ foo
foo
$
Note that FUNCNAME becomes an array starting from bash 3.0 but the above
code still works because $array is the same as ${array[0]}.
> β
> β
>
> On Tue, Jul 28, 2015 at 11:12 PM, Clark Wang <address@hidden> wrote:β
>
> Or you can change current shell's $*N* like this:
>
>
This is not accurate. Functions can have their own positional parameters.
>
> # echo "<$0> <$1> <$2>"
> </Users/clarkw/utils/bin/bash> <> <>
> # set -- -a
> # echo "<$0> <$1> <$2>"
> </Users/clarkw/utils/bin/bash> <-a> <>
> # set -- -al
> # echo "<$0> <$1> <$2>"
> </Users/clarkw/utils/bin/bash> <-al> <>
> # set -- -al bar
> #
> ββ
> echo "<$0> <$1> <$2>"
> </Users/clarkw/utils/bin/bash> <-al> <bar>
> #
>
>
> Fascinating! Why doesn't this work?
>
> β$ foo() { echo $0 $1 $2 $3 $4; }
> $ foo -a -b -c
> bash -a -b -c
> $
> β
> echo "<$0> <$1> <$2>"
> bash <> <>
>
> Is it because 'foo()' is run in a subshell and 'echo "<$0> <$1> <$2>"' is
> run in the parent shell? If so, then the set command is not run in a
> subshell, right?
>
It's not run in a subshell. Functions have their own $*N* vars can they
would not affect the current shell's $*N* (just like *local* vars in
functions).
-clark