Variables value gets lost in subshell

前端 未结 5 1290
忘了有多久
忘了有多久 2020-12-21 09:57

This bash script concatenates the names for jar files to a classpath (variable CP), in the while loop the value is correct but is lost in the subshell as descibed in this re

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 10:21

    Implicit subshells are confusing; always make them explicit by using parentheses. To solve your problem, just move the echo inside the subshell.

    #!/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
    

提交回复
热议问题