Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment a variable in bash ` i=0; ls>$((++i)); echo i=$i; ` why the result is i=0

Tags:

bash

shell

case 0

i=0; ls > $((++i)); echo i=$i

create a file : 1

and output:

i=0

comment: why i=0 ?

case 1

i=0; ls $((++i)); echo i=$i

output:

1

i=1

comment: the result is correct

case 2

i=0; echo > $((++i)); echo i=$i

create a file : 1

and output:

i=1

comment: the result is correct

case 3

i=0; echo 1 | grep $((++i)); echo i=$i

output:

1

i=0

comment: maybe case 3 <=> case 0 ?

case 4

i=0; command ls > $((++i)); echo i=$i

create a file : 1

and output:

i=1

comment: why diff with case 0 ?

case 5

i=0; { ls; } > $((++i)); echo i=$i

create a file : 1

and output :

i=1

comment: this case from gniourf_gniourf

more cases:

i=0; ( echo ) > $((++i)); echo i=$i   #i=0

i=0; { ls > $((++i)); }; echo i=$i   #i=0

I am very confused, why i=0 in case 0 ?

Whether it is a bug ?

My bash version : GNU bash, version 3.2.25(1)-release (i686-redhat-linux-gnu)

You can try in your bash.

like image 477
赵小刚 Avatar asked Sep 29 '22 09:09

赵小刚


1 Answers

The difference between echo and ls is that ls is an external command /usr/bin/ls, while echo is a shell builtin. Try replacing it with /usr/bin/echo (if it exists on your system). You'll get the same behaviour - it seems the redirection happens in a subshell that runs the command.

Compare:

$ i=0; /usr/bin/echo > $( ((++i)); echo inside $i>&2; echo $i ) ; echo i=$i
inside 1
i=0
like image 90
choroba Avatar answered Oct 10 '22 05:10

choroba