![find & while [반복] 후에 변수는 변경되지 않습니다.](https://linux55.com/image/86901/find%20%26amp%3B%20while%20%5B%EB%B0%98%EB%B3%B5%5D%20%ED%9B%84%EC%97%90%20%EB%B3%80%EC%88%98%EB%8A%94%20%EB%B3%80%EA%B2%BD%EB%90%98%EC%A7%80%20%EC%95%8A%EC%8A%B5%EB%8B%88%EB%8B%A4..png)
내 코드
var=34
find $1 -type f | while read line;
do
file_status=`file "$line"`
file_name=`echo $line | sed s/".*\/"//g`
line_length=${#file_name}
if [ $line_length -gt $n ]; then
echo "hi there"
var=$((var+1))
fi
done
echo $var
hi 메시지가 여러 번 표시되지만 while 루프를 완료한 후에는 내 변수가 34가 됩니다.
답변1
파이프( |
)를 사용했고 파이프 주변의 명령이 서브셸에서 실행되기 때문입니다.
따라서 해당 서브쉘에서 변수의 값이 var
변경(증가)되고 서브쉘이 종료되면 범위를 벗어나므로 부모 쉘의 값에는 아무런 영향을 미치지 않으므로 부모 쉘의 값은 34로 유지된다.
이 문제를 해결하려면 프로세스 대체를 사용하여 다음을 실행할 수 있습니다 find
.
var=34
while read line; do
file_status=`file "$line"`
file_name=`echo $line | sed s/".*\/"//g`
line_length=${#file_name}
if [ $line_length -gt $n ]; then
echo "hi there"
var=$((var+1))
fi
done < <(find $1 -type f)
echo $var