0

I have a script that exports log files, usually I get between 1-3 separate files depending on the size of the log for a particular day. After the export I run a report generator to spit out an html document of those logs. My question is how to call the command that generates the reports depending on the number of files, I know I can use if statements and do:

./generateReport -i file1 -o output.html

./generateReport -i file1 file2 -o output.html

./generateReport -i file1 file2 file3 -o output.html

is there a way to loop over the files and include them as an input??

3
  • It would be more conventional to use -i file1 -i file2 -o output.html, or to remove -i altogether (file1 file2 -o output.html) Commented Sep 4, 2013 at 15:21
  • Use positional parameters rather than flags for multiple input files. Commented Sep 4, 2013 at 15:58
  • Was the question how to implement generateReport (to parse names off the command line when called through the given convention), or how to call generateReport? I read it as the former. Commented Mar 25, 2017 at 17:34

3 Answers 3

3

Is it necessary to use flags?

./generateReport file1 file2 file3 > output.html
Sign up to request clarification or add additional context in comments.

1 Comment

Yes it is, since I am using a tool to generate logs and it uses -i to start reading input files to it
2

The following will collect an array of inputFiles, and a single variable with the output file name:

inputFiles=( )
outputFile=
while (( $# )); do
  if [[ $1 = -o ]]; then
    outputFile=$2; shift
  elif [[ $1 = -i ]]; then
    inputFiles+=( "$2" ); shift
  else
    inputFiles+=( "$1" )
  fi
  shift
done

...then, you could do something like this:

# redirect stdout to the output file, if one was given
[[ $outputFile ]] && exec >"$outputFile"

# loop over the input files and process each one
for inputFile in "${inputFiles[@]}"; do
  process "$inputFile"
done

Comments

1

Try filename expansion :

./generateReport -i file? -o output.html

or using find for all log files created in the last 24 hours :

./generateReport -i `find . -name "file*" -mtime -1` -o output.html

1 Comment

The second one is buggy, if any of your filenames contain spaces in them. See also BashPitfalls #1, which applies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.