Bash – How to create a Bash conditional script, based on output from a command

bashfilesforshell-scriptUbuntu

I have a Java program that gets two arguments (a video file name and an image) and outputs a boolean (0 or 1) in the first line:

java -jar myProgram video1.mp4 image.png
> 0
>some extra information...
>other extra information....going on

Now using bash script, I need to iterate through all files in a folder (not files in nested folders), run the program with the file name passed to the first argument (video name changes everytime, and image is fixed), and if the output in the first line is 0, copy the file in folder0, and if the output is 1, copy the file to folder1.

How can I achieve that in bash?

Best Answer

You have much better control when using conditional statements:

for file in *; do
   if [[ -f "$file" ]]; then
      output=$(java -jar myProgram "$file" image.png | head -n 1)
      [[ $output = "0" ]] && cp -- "$file" folder0
      [[ $output = "1" ]] && cp -- "$file" folder1
   fi
done

EDIT: if you still want to see the output of java, you can use this:

output=$(java -jar myProgram "$file" image.png | tee /dev/tty | head -n 1)
Related Question