0

I'm trying to make a bash script to execute a C++ code multiple times and insert the output on a file, but it execute a single time producing one file with the expected output.

I tried adding a sleep command but does not worked.

#!/bin/bash
thrd=2
comm="./""Segmentation $thrd"
for i in $(seq 1 30)
do
    echo "${i}"
    exec $comm > outputs/file${i}.txt
    sleep 1s
done
Shinforinpola
  • 200
  • 1
  • 15
  • Why do you use `exec`? – Benjamin W. Aug 30 '20 at 00:42
  • 3
    Remove the `exec` command -- it *replaces* the shell that's running your script with the command, hence implicitly terminating the script. BTW, the quoting in `comm` is weird and may not do what you think. Storing commands in variables is generally a bad idea; see [BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) – Gordon Davisson Aug 30 '20 at 00:52
  • I started today with it and I saw some content and tried this. I thought the `exec` was mandatory and I didn't even think about trying without. Thank you so much! – Shinforinpola Aug 30 '20 at 01:03
  • 1
    Not relevant to your root problem, but in `bash`, use `for ((i = 1; i <= 30; ++i))` instead of `for i in $(seq 1 30)`. Calling an external command is unnecessary. – M. Nejat Aydin Aug 30 '20 at 01:25
  • 1
    or `for i in {1..30}`. – Benjamin W. Aug 30 '20 at 04:49
  • Tip: [ShellCheck](https://www.shellcheck.net) automatically detects this and other common issues. – that other guy Aug 30 '20 at 06:08

1 Answers1

-2

You could just use a standard shell script. You can also call sh on a file and it will be interpreted correctly.

#!/bin/sh
for i in $(seq 1 30)
do
    echo $i
    sh ./binaryName arg1 arg2 > outputs/file$i.txt
done
xddq
  • 341
  • 3
  • 7
  • 1
    Don't use `sh` like this. If the file is a script, set the [shebang line](https://stackoverflow.com/questions/3009192/how-does-the-shebang-work) properly, make the file executable, and just run it directly. Using `sh` can cause problems if the script requires bash features, and `sh` is something more basic (Debian, Ubuntu, probably others). If it's not a shell script at all, trying to run it with `sh` will just plain fail. – Gordon Davisson Aug 30 '20 at 02:20