1

I want to repeatedly run multiple commands at a time interval using a script. I tried this

----------------test_script---------------
while true;do 
ls -l >>output.txt
sleep 3
done


while true;do 
cat file.txt 
sleep 5
done

i want to run both while loops at same time .When i run the above script ,only first while loop is running and the output of ls -l is redirected to the file .How i can execute both while loops simultaneously from the script

Adhz
  • 55
  • 7
  • 1
    You are anyway running infinite loops. So why not put both `ls` and `cat` in the same `while`. – Fazlin Jul 15 '16 at 09:56
  • 1
    Use `&` to run a command in background. – choroba Jul 15 '16 at 10:01
  • @choroba : But this is a bit involved than that. Perhaps I was looking at one of your earlier [\[ solution \]](http://stackoverflow.com/a/19543286/1620779). – sjsam Jul 15 '16 at 10:05
  • 1
    @ Fazlin my intention was to run both commands at specified time intervel repeatedly. If running from same while loop i have to consider other delays also ,if a am running 5 commands like this ,the first command will run for the second time after going through all the other 4 commands. – Adhz Jul 15 '16 at 10:07
  • @Adhz: Please provide your suggestions/observations on the provided answer(s), so that it will be useful to help you out further! – Inian Jul 15 '16 at 10:51

1 Answers1

1

One way to do is run one of the loops in the background and other in the fore like below.

#!/bin/bash

while true;do 
    ls -l >>output.txt
    sleep 3
done &             # Runs the first while loop in the background and passes to the next while loop

while true;do 
    cat file.txt 
    sleep 5
done
Inian
  • 80,270
  • 14
  • 142
  • 161
  • It would be more efficient to redirect to `output.txt` only once, after the `done`. Then you can use an overwriting rediect if you like, to clear any previous contents in the file. – tripleee Jul 16 '16 at 06:10