简体   繁体   中英

How do I “tee” variable number of times in a bash “for loop”?

I understand I can:

ssh archive_server -l user -n "cat text.csv"|tee -a text1.csv|tee -a text2.csv|tee....|tee -a text10.csv

Is there a way to do it aa loop?

for i in `seq 1 10`; do
  echo $i
  tee ???
done

Assuming your shell is really bash (not /bin/sh ), you can build an array (and use a C-style for loop , which unlike the nonstandard external command seq , is guaranteed to be available everywhere bash is):

#!/bin/bash
filenames=( )
for ((i=1; i<=10; i++)); do    # note that the "10" here can be a variable name
  filenames+=( "file$i.txt" )
done
tee -a -- "${filenames[@]}" <text.csv

If you need compatibility with /bin/sh , it gets a little bit more verbose:

#!/bin/sh
tee_between() (
  prefix=$1; suffix=$2; start=$3; end=$4
  set --
  i=$(( $start - 1 )); while [ $(( ( i += 1 ) <= end )) -ne 0 ]; do
    set -- "$@" "file$i.txt"
  done
  exec tee -a -- "$@"
)

tee_between "file" ".txt" 1 10 <text.csv

Note:

  • set -- modifies the current process's (or, in this case, the current function's) argument list, using that as an array we can dynamically modify.
  • tee_between() ( ) instead of tee_between() { } means that the function runs in a subshell -- a completely separate forked-off process. In consequence of this choice, the exec command will replace only that subshell with a copy of tee , and not the parent process.

You don't need a loop. tee can be given multiple filename arguments, so just give all the output files at once:

cat text.csv | tee -a text{1..10}.csv

If the number of files is dynamic, you can use a loop in $() to insert the filenames into the command line:

cat text.csv | tee -a $(
    for i in $(seq 1 $filecount); do
        echo text$i;
    done)

Just make sure that you don't have any whitespace in the output filename prefix, as the spaces will be treated as argument delimiters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM