Variable values ​​are lost in the subshell

This bash script concatenates jar file names in the classpath (CP variable), in the while loop this value is correct, but is lost in the subshell, as described in this related question Bash variable area

#!/bin/bash
CP="AAA"
func() {
        ls -1 | while read JAR
        do
                if [ ! -z "$CP" ]; then
                        CP=${CP}':'
                fi
                CP=${CP}${JAR}
        done
        echo $CP # <-- prints AAA
}

func

My question is that I cannot figure out which element will be the last, how to store the value.

Do I really need to save the current value (repeatedly in a loop) to a file?

EDIT:

A colleague came up with this command sequence that works well

ls | xargs echo|tr ' ' :
+3
source share
5 answers

, while , . . , , :

for JAR in *; do
    # Your stuff
done

, : ls

.

+6

, .

:

export CP=$( find /home/depesz/q/ -maxdepth 1 -type f -name '*.jar' -printf ':%p' | cut -b 2- )

, , /.

, :

export CP=$( find . -maxdepth 1 -type f -name '*.jar' -printf ':%f' | cut -b 2- )
+1

; . , .

#!/bin/bash
CP="AAA"
func() {
  ls -1 | (
    while read JAR
    do
      if [ ! -z "$CP" ]; then
        CP=${CP}':'
      fi
      CP=${CP}${JAR}
    done
    echo $CP
  )
}
func
0

, . , ( "JARS" ), , < EOF:

JARS=$(ls -1)

while read JAR
do
        if [ ! -z "$CP" ]; then
                CP=${CP}':'
        fi
        CP=${CP}${JAR}
done <<EOF
$JARS
EOF

echo $CP
0

, , , , , script , . , , , , temp, (, ):

#!/bin/bash
CP="AAA"
func() {
  ls -1 | (
    while read JAR
    do
      if [ ! -z "$CP" ]; then
        CP=${CP}':'
      fi
      CP=${CP}${JAR}
    done
    echo "$CP" > /tmp/cp-value-file
  )
}

func
CP=$(cat /tmp/cp-value-file)
echo $CP

: .

0
source

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


All Articles