Increment a variable in bash `i = 0; Ls> $ ((++ i)); echo i = $ i; `why the result i = 0

case 0

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

create file: 1

and conclusion:

= 0

comment: why i = 0?

case 1

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

exit:

1

= 1

comment: correct result

case 2

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

create file: 1

and conclusion:

= 1

comment: correct result

case 3

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

exit:

1

= 0

comment: perhaps case 3 <=> case 0?

case 4

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

create file: 1

and conclusion:

= 1

comment: why diff in case 0?

case 5

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

create file: 1

and conclusion:

= 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 am I = 0 in case 0?

Is this a mistake?

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

You can try in bash.

+5
source share
1 answer

The difference between echo and ls is that ls is the external command /usr/bin/ls , and echo is the built-in shell. Try replacing it with /usr/bin/echo (if it exists on your system). You will get the same behavior - it seems that the redirection occurs in the subshell that runs the command.

For comparison:

 $ i=0; /usr/bin/echo > $( ((++i)); echo inside $i>&2; echo $i ) ; echo i=$i inside 1 i=0 
+4
source

Source: https://habr.com/ru/post/1207389/


All Articles