Can somebody show me how to make a program to do this action: after 5 minutes
echo "80" > /sys/class/leds/blue/brightness
I want this program run in the background (like rngd
service)
I can't do this because I don't know so much about Linux.
( sleep 300 ; echo "80" > /sys/class/leds/blue/brightness ) &
That way your script continues, or you restore control immediately, while a new background task of the script starts, with two commands: sleep, and echo.
The common error is trying to give either sleep
or echo
or both the &
which will not work as intended. Launching a series of commands in ()
though spawns them in a separate shell process, which you can then send whole into background with &
.
To that wit, where I found it actively useful. In an embedded device I develop there's the main application that works with a watchdog. If it fails in a way that triggers the watchdog reset soon after startup, repeatedly, it's hard to fix remotely as the period between the OS start and the reset is quite short, not enough to ssh in, and block the app startup. So I need a way to determine the system restarted so fast and introduce a delay if it did, to give myself time to fix it manually.
[ -f /tmp/startdelay ] && sleep 30
touch /tmp/startdelay
( sleep 30 ; rm /tmp/startdelay ) &
[ -f /tmp/noautostart ] && exit 0
start_app
If I log in and perform touch /tmp/noautostart
the main app won't start. If the watchdog kicks in, rm /tmp/startdelay
won't be performed and the next time the system starts, it will give me extra 30s to stop it. Otherwise restart will be quick, without delay.
wait 10; killall X
allowed me to test it without having to reboot every time.
use the at
command
echo "echo \"80\" > /sys/class/leds/blue/brightness" | at now + 5 min
that will run in the background
echo
altogether by using a heredoc or herestring.
Commented
Dec 2, 2013 at 15:49
If you want something to run in 5 minutes, but the rest of your program to continue (or finish), you need to background the sleep as well:
#!/bin/bash
runWithDelay () {
sleep $1;
shift;
"${@}";
}
runWithDelay 3 echo world &
echo hello
This will print hello
and then 3 seconds later (after the main program has exited), print world
.
The important part is the &
to fork the function execution into the background.
runWithDelay () { sleep $1; "${@:2}"; }
instead?
Commented
Nov 28, 2013 at 15:00
doWhateverWithDelay 3 &
in your second example.
$@
is that you can quote it and will be expanded as list of quoted words. So better make it "$@"
(or "${@}"
if you like the braces). See pastebin.com/MU7hbB2C
Commented
Nov 28, 2013 at 15:15
-n
), but obviously that was a bit naive.
Commented
Nov 28, 2013 at 20:32