Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use command "at" to execute shell in MacOS

Tags:

shell

macos

I want to execute some shell script once in MacOS.

At first, I tried the "at" command in Ubuntu and it performed well. But when I use same method in MacOS, things goes wrong

I typed:

$ at now + 2 minutes
ls -al > tmpfile
(ctrl+d,EOF)

The job was added successfully.

The output of "at -l" is:

(some other output)
11         Fri  Jul  19  15:18:00  2013

But after 15:18 ,tmpfile was not changed.

I want to know how to use "at" command in MacOS corectly or is there any other method to execute some shell script at certain time once(not periodic)

like image 792
taoch Avatar asked Jul 19 '13 07:07

taoch


2 Answers

I noticed "SEE ALSO" in man page of at:

SEE ALSO
nice(1), sh(1), umask(2), campact(5), atrun(8), cron(8), sendmail(8)

In atrun(8), a solution is provided.

Execute the following command as root to enable atrun:
launchctl load -w
/System/Library/LaunchDaemons/com.apple.atrun.plist

After I sudo this command, and then restart my computer, at become available.

like image 183
taoch Avatar answered Nov 09 '22 06:11

taoch


Using at

Your use of at appears correct. The command is executed at 2 minutes in the future. The command is not executed repeatedly so that is why the file is not touched at any time other than the time that now + 2 minutes evaluates to.

If you are having problems getting at to run commands make sure you have the atrun Launch Control agent enabled and runing. See man atrun for more information about that.

Better Scheduled Command Execution

If you just want something executed when you log in then System Preferences > Users > Login Items is a good place. Rename your shell scripts with .command as their extension though if you do that. I'm not sure if it is required but it's what the OS seems to prefer for such scripts.

Otherwise try cron to provide more control over job execution or use launchd, the mac launch control daemon (see man launchd and man launchctl). Have a read of this blog post which seems a good introduction to the use of the OS X Launch Control Daemon.

Launchd is the preferred way of scheduling commands on mac, I only mention cron here as it may be more familiar if you are coming from a Linux background.Take a look at this answer for more details about that.

like image 27
Will Avatar answered Nov 09 '22 05:11

Will