Stop an application in bash after a certain amount of time

You can use the timeout command to run a command with a time limit. Its basic syntax is:

timeout DURATION COMMAND

where DURATION is a floating point number with the suffix s for seconds, m for minutes, h for hours or d for days and COMMAND is the command you wish to run.

In your case, you can use:

timeout 10s vlc -vvv http://10.0.0.113:8000/stream.mjpg --sout="#std{access=file,mux=ogg,dst=/home/whsrobotics/vlc_project/first_try.mp4}"

to run your command for 10 seconds and then kill it.


Add & after the second line to put VLC in the background like so:

#!/usr/bin/bash
vlc -vvv http://10.0.0.113:8000/stream.mjpg --sout="#std{access=file,mux=ogg,dst=/home/whsrobotics/vlc_project/first_try.mp4}" &
sleep 10
killall vlc

and it will work.


Explaination:

The shell/terminal will execute commands in the order they are listed in the script and will move to the next command only if the command before it finishes executing.

Which is not the case in your VLC command. As long as VLC is running, the shell/terminal will consider it still executing and will not move to the command after it but will rather wait for it to finish executing ( ie. in this case closing the VLC window/instance ).

A workaround this is to send VLC to the background and free the shell/terminal prompt for the next command in the script. Which can be done by adding & after the command.


Notice:

  • Remove verbosity option -vvv to avoid the script not exiting cleanly and completely.

  • If, however, you have to use the verbosity option -vvv add nohup before the second line as well like so:

#!/usr/bin/bash
nohup vlc -vvv http://10.0.0.113:8000/stream.mjpg --sout="#std{access=file,mux=ogg,dst=/home/whsrobotics/vlc_project/first_try.mp4}" &
sleep 10
killall vlc

This will append output to a file called nohup.out in the current working directory if possible or to ~/nohup.out otherwise and will allow the script to terminate cleanly and completely.

See man nohup for information.

Best of luck


This is probably the most elegant answer (only works with VLC of course):

#!/usr/bin/bash
vlc -vvv --stop-time 10 --play-and-exit http://10.0.0.113:8000/stream.mjpg --sout="#std{access=file,mux=ogg,dst=/home/whsrobotics/vlc_project/first_try.mp4}"

--stop-time 10 Will stop playback after 10 seconds
--play-and-exit Will exit VLC after playback stopped (default is --no-play-and-exit)

In some cases you need to use --run-time instead of --stop-time.