4

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?

2
  • Are the > signs part of the output?
    – ilkkachu
    Dec 6, 2017 at 22:01
  • oh no. Just to show it is output!
    – Tina J
    Dec 6, 2017 at 22:04

2 Answers 2

3

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)
8
  • I only changed the 0 and 1 to false and true, but I get error:
    – Tina J
    Dec 7, 2017 at 16:25
  • runme.sh: line 4: conditional binary operator expected runme.sh: line 4: syntax error near "true"' runme.sh: line 4: ` [[ $output= "true" ]] && cp -- "$file" video'`
    – Tina J
    Dec 7, 2017 at 16:25
  • Even with the original 0 and 1 id shows the same error.
    – Tina J
    Dec 7, 2017 at 16:41
  • 1
    @TinaJ There has to be the space before =. So it should be $output = 1.
    – PesaThe
    Dec 7, 2017 at 16:55
  • 1
    @TinaJ Please, read on filename expansion in bash, for file in *.mp4...
    – PesaThe
    Dec 7, 2017 at 17:48
2

Something like:

for f in source/*
do
    cp "$f" folder$(java -jar myProgram "$f" image.png | head -1)
done
9
  • Where is the condition then?
    – Tina J
    Dec 7, 2017 at 16:40
  • 1
    Replace source/* by current/*.mp4 Dec 7, 2017 at 17:00
  • 1
    This is expected, the script just run the cp command to copy files and the java command output is captured inside the $(...) construct, there should be no output except if problems. Dec 7, 2017 at 17:06
  • 1
    @TinaJ Yes, you can achieve that with tee. You can read about tee in manual and refer to my answer for solution.
    – PesaThe
    Dec 7, 2017 at 19:20
  • 1
    Thanks. Both answers are great. I have a hard time selecting the answer. The other one was 5 min faster ;)
    – Tina J
    Dec 7, 2017 at 19:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .