循环后变量值复位

时间:2018-05-01 22:24:54

标签: bash shell

这是一个简单的脚本,用于连接文件名以创建要创建的表的列表。

tabnames.bash

#!/bin/bash
ADDITIONALTABLES="FXRATES ANVIL"
ls /abc/static/rtce_reports/static/*.csv | while read staticFile
do 
   staticTable=`basename $staticFile`
   echo $staticTable
   ADDITIONALTABLES=$ADDITIONALTABLES" "${staticTable%.csv}
   echo $ADDITIONALTABLES
done
echo $ADDITIONALTABLES

文件是:

$ ls /abc/static/rtce_reports/static/*.csv
/abc/static/authority.csv
/abc/static/creditRating.csv
/abc/static/creditdept.csv
/abc/static/currency.csv
/abc/static/organiationType.csv
/abc/static/sector.csv

以下是输出:

$ ./tabnames.bash
authority.csv
FXRATES ANVIL authority
creditRating.csv
FXRATES ANVIL authority creditRating
creditdept.csv
FXRATES ANVIL authority creditRating creditdept
currency.csv
FXRATES ANVIL authority creditRating creditdept currency
organiationType.csv
FXRATES ANVIL authority creditRating creditdept currency organiationType
sector.csv
FXRATES ANVIL authority creditRating creditdept currency organiationType sector
FXRATES ANVIL

一旦失去循环,ADDITIONALTABLES的值将重置为其在进入循环之前保持的值。

为什么?

1 个答案:

答案 0 :(得分:1)

这样做:

#!bin/bash
#
ls *.csv > /tmp/CSVfiles
ADDITIONALTABLES="FXRATES ANVIL"
while read staticFile
do 
   staticTable=`basename $staticFile`
   echo $staticTable
   ADDITIONALTABLES="$ADDITIONALTABLES ${staticTable%.csv}"
   echo "in $ADDITIONALTABLES"
done < /tmp/CSVfiles
echo "out $ADDITIONALTABLES"

与评论中指出的其他人一样,管道在子shell中运行。但是,如果你像上面那样使用重定向,那就可以了。

相关问题