Linux shell error? Variable assignment in pipe does not work

Why FILE_FOUND is 0 at the end of this bugger:

FILE_FOUND=0

touch /tmp/$$.txt

ls -1 /tmp/$$.* 2>/dev/null | while read item; do
    FILE_FOUND=1
    echo "FILE_FOUND = $FILE_FOUND"
done

echo "FILE_FOUND = $FILE_FOUND"

rm -f /tmp/$$.txt 2>/dev/null

?? !!

On Unix, FILE_FOUND remains 1 (as it should be), but on Linux (RedHat, Cygwin, ..) it returns to 0 !!

Is this a Linux shell, not a bug? :)

Please, help.

+3
source share
6 answers

a common problem is that you are connecting to while, so it runs in a subshell that cannot pass environment variables back to parents. I assume that "unix" is different in this respect, since you are using a different shell there (ksh?)

, while. ?

for item in /tmp/$$.*; do
    ....
done

, - , :

touch /tmp/file_found
+5

"" "bash" . "bash" :

(.. ).

, Korn ( "ksh" ), "while" ( ) , , . .

POSIX , " ", , UNIX/Korn , Bourne Again - . "bash" POSIX!

+3

, , while . , "Unix", , , Solaris, bash .

, , while - ,

result=`mycommand 2>/dev/null | while read item; do echo "FILE_FOUND"; done`

$result. , while .

eval `mycommand | while read item; do echo "FILE_FOUND=1"; done`

"" .

, ,

for item in /tmp/$$.*; do
  # whatever you want to do
done
+2

, , , . :

while read item; do
    FILE_FOUND=1
    echo "FILE_FOUND = $FILE_FOUND"
done < <(ls -1 /tmp/$$.* 2>/dev/null)

while script, ls - ( , script).

+2

-, ,

FILE_FOUND=0
result=$(echo "something" | while read item; do
    FILE_FOUND=1
    echo "$FILE_FOUND"

done )
echo "FILE_FOUND outside while = $result"
0

Ummmm ... ls -1not llocated on your script?

-2
source

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


All Articles