0

I want to run bash in a specific time(With at command ) for 3 minutes after that, I want to shut down the machine

This is my bash code (send.sh) :

$ x=10
echo The value of variable x = $x

and this is my at command :

at 2:30 PM tomorrow

what should I write in send.sh for running for 3 minutes and then shutting down the machine

hlovdal
  • 23,353
  • 10
  • 78
  • 148
majid
  • 672
  • 1
  • 8
  • 32

2 Answers2

1

I don't understand why you want to execute the "waiting" part inside of your script: you can simply do the following, using at (pseudo-code):

at 2:30 PM tomorrow, launch "send.sh"
at 2:33 PM tomorrow, shut down your machine

The problem is that, if you put it somewhere in "send.sh", the following might happen:

send.sh content:

<do something>
<wait for three minutes>
<shut down your machine>
  1. The <do_something> might take some time, and the shut down will be launched later than the expected three minutes.
  2. The <do_something> might go wrong, causing your script to abort and your machine won't be shut down at all.

Hence my proposal to create two separate at entries.

Edit, after comment from Socowi:

Apparently, one can add an at-clause after a command, as follows:

echo shutdown | at now + 3 minutes

This might be the solution you're looking for.

Dominique
  • 8,687
  • 9
  • 28
  • 67
  • The second `at` command can be added to the top of the script, so that a shutdown is scheduled automatically each the time script runs: `echo shutdown | at now + 3 minutes`. – Socowi Aug 15 '20 at 12:40
1

The timeout command might be what you're looking for.
It will send a TERM signal to the running command after a specified amount of time. Additionally, you can specify that it will send an additional KILL signal in case that the command is reluctant to react to the TERM signal.
Here is a sceleton script that you can modify for your purpose:

#!/bin/bash

{ sleep 180; echo shutdown; } &

timeout --verbose --kill-after 1 180 \
    bash -c "trap 'echo TERM received, exiting gracefully!; exit' SIGTERM; while true; do sleep 1; echo Sending stuff...; done"

The whole purpose of my while loop is to simulate something that might be going on for more than 3 minutes. I've added a signal trap that gets fired once the TERM signal has been sent, in order to give the script a chance to exit gracefully when its time has come. Remove the echo in front of the shutdown once you've tested your script and you're satisfied with the result.

Here's the script in action:

~/$ ./send.sh 
Sending stuff...
Sending stuff...
  (truncated)
Sending stuff...
timeout: sending signal TERM to command ‘bash’
shutdown
Terminated
TERM received, exiting gracefully!
lab9
  • 586
  • 8