How to start and kill application with shell script

GOAL

Start an application and kill it after a certain time.

Environment

macOS Catalina 10.15.5

ShellScript

sleep.sh

#!/bin/sh
open -a MyApp
sleep 60
killall MyApp
echo "stop"

open

The command “open” can open files and it takes some options. You can see options here. The -a option is for application.

open -a MyApp

kill/killall

The commands “kill” and “killall” can kill processes. “kill” takes PID(process id) and “killall” takes process name. You can stop and close an application with this command.

killall MyApp

sleep

The command “sleep” can delay for a specified time. Though “sleep” can take quantifiers such as 10s(second), 10m(minutes) and 10h(hours) in Linux, it can take number as seconds in OSX ([Tips]Why command “sleep 1m” doesn’t work in mac).

sleep 60

Execution

Open the terminal and input the sh file name.

 % Documents/sh/sleep.sh 

If the permission error occurred, change access permission with “chmod” command.

$ chmod +x sleep.sh