0

Here is a simple script to concat file names to make a list of table to be created.

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

the file are:

$ 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

below is the output:

$ ./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

as soon as it goes out of loop, the value of ADDITIONALTABLES is reset to its value it held before entering the loop.

Why?

techie11
  • 1,243
  • 15
  • 30
  • 1
    Because pipeline runs in a subshell. – choroba May 01 '18 at 22:39
  • See [BashFAQ #24: "I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?"](http://mywiki.wooledge.org/BashFAQ/024) – Gordon Davisson May 01 '18 at 23:55
  • Actually, in this case it'd be better to use `for staticFile in /abc/static/rtce_reports/static/*.csv; do` -- this doesn't have the subshell problem, and also avoids possible [ambiguity in `ls`'s output`](http://mywiki.wooledge.org/ParsingLs). – Gordon Davisson May 02 '18 at 01:55
  • Good idea. thanks. – techie11 May 02 '18 at 04:00

1 Answers1

1

Do it this way:

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

Like others pointed out in the comments, the pipe runs in a subshell. But if you use redirection like above it works.

Nic3500
  • 8,144
  • 10
  • 29
  • 40