I am interested in running a bash script which starts an application (in this case VLC), run it for a certain amount of time and then stop it. I can get this application to start just fine, but it will not stop, using this script:
#!/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
Not only does it not stop the stream recording, but the app seems to freeze sometimes after I hit Ctrl+Z.
Any suggestions are appreciated.
You can use the
timeout
command to run a command with a time limit. Its basic syntax is:where
DURATION
is a floating point number with the suffixs
for seconds,m
for minutes,h
for hours ord
for days andCOMMAND
is the command you wish to run.In your case, you can use:
to run your command for 10 seconds and then kill it.
Add
&
after the second line to putVLC
in the background like so: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 asVLC
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 theVLC
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
addnohup
before the second line as well like so: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):
--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
.I am pretty sure that this question will be found by people wanting to stop other programs, not just
vlc
on systems that do not have thetimeout
command, so in extension to the already good generic answer by Raffa:Your attempt would kill all
vlc
processes in the system, not just the one started by this script. Instead you can use thekill
built-in, as it can accept a bash job specification. For example:The
&
operator in the second line will create a background bash job. Thenkill %?vlc
will kill the bash job whose prefix isvlc
.