Code:
for TABNAME in $(cat tables_list.log); do
get_stats () {
./ggsci >> $STATSLOG 2>&1 <<EOF
stats replicat $REPNAME, latest, $TABNAME
exit
EOF
}
Don't Read Lines With For (and
Useless Use Of Cat too). You should always use a
while+read loop when reading data from a file or command. More here:
How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?
http://mywiki.wooledge.org/BashFAQ/001
Also, don't put the function definition inside the loop. You don't need to redefine it every time. Functions are "write once, use many" structures.
There are two possible choices here. You could put the loop inside the function, or you could keep the function as is, and run it multiple times in a loop.
Code:
#First choice:
get_stats () {
local TABNAME TABFILE=/path/to/tables_list.log
while read -r TABNAME || [[ -n $TABNAME ]]; do
./ggsci >> "$STATSLOG" 2>&1 <<-EOF
stats replicat $REPNAME, latest, $TABNAME
exit
EOF
done <"$TABFILE"
}
Code:
#Second choice:
get_stats () {
./ggsci >> "$STATSLOG" 2>&1 <<-EOF
stats replicat $REPNAME, latest, $1
exit
EOF
}
TABFILE=/path/to/tables_list.log
while read -r TABNAME || [[ -n $TABNAME ]]; do
get_stats "$TABNAME"
done <"$TABFILE"
It's a good idea to define all function-only variables as local. It keeps the possibility of conflicts down. (I'm assuming here that STATSLOG and REPNAME are global variables, otherwise they too should be defined locally.)
The
[[ -n $TABNAME ]] test ensures that the last line of the file will always be processed, even if there's no final newline. See the above link for more on that.
The "
<<-" form of a here document allows you to indent the rest of it with
tabs (and only tabs), without affecting the resulting input. All leading tabs will be removed before processing. It helps keep your formatting clean.
Finally,
QUOTE ALL OF YOUR VARIABLE EXPANSIONS. You should never leave the quotes off a parameter expansion unless you explicitly want the resulting string to be word-split by the shell and any possible globbing patterns expanded. This is a vitally important concept in scripting, so train yourself to do it correctly now. You can learn about the exceptions when you need them.
http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes
(Note, however, that variables inside heredocs should NOT be quoted, since no shell processing other than variable/command substitution occurs inside them. They're just more text inside a heredoc.)