Category Filter

Mac Shell Scripting Resources

With Hexnode UEM, you may remotely execute scripts on devices running macOS 10.11 and above. This document equips you with a collection of shell scripts that Mac admins may find useful in their workflows.

Disclaimer:

THE SAMPLE SCRIPTS PROVIDED BELOW IS ADAPTED FROM THIRD-PARTY OPEN-SOURCE SITES.

Notes:

To execute custom script on a Mac with Hexnode UEM, you need a script file which can be of the following formats –

Perl (.pl), Bash (.sh), Shell (.sh), C Shell (.csh), Zsh (.zsh), Korn Shell (.ksh), Hypertext Preprocessor (.php), Ruby (.rb), and Python (.py).

For this document, we are using Bash, and the script file should be saved with the extension .sh.

Once you’ve prepared the script, navigate to Manage > Devices > [Find your device], select Actions > Execute Custom Script; this will open a window for you to upload the script file, enter the binary path to run on and the script arguments. Confirm to execute the script.

To view the script output for a device, go to the Action History sub-tab on the device details page and click on Show Output for the script action.

Echo command

echo argument

The echo command writes arguments to the standard output. When you manually run the script on the Mac Terminal, this will display the output on the Terminal window. When you run the script remotely on the device with Hexnode, you can see the output with the Show Output link under Action History on the device page.

Click on Show output to view echo output

The argument here can be passed as a string –

echo Hello

Or as an argument or wildcard.

Hexnode supports the following wildcards –

  • %devicename%
  • %deviceid%
  • %wifimacaddress%
  • %name%
  • %domain%
  • %email%
  • %imei%
  • %username%
  • %department%
  • %assettag%
  • %devicenotes%

To use wildcards, pass the wildcards as arguments separated by a blank space.

use a single space to separate your arguments

The wildcard will be automatically included in the code as an argument.

Example – echo $1, $2 becomes echo devicename, name

App management

Open an app

#!/bin/bash
open –a “App name"

The open command can be used to open a file, directory or URL. Some of the options supported with the open command in this respect are –

  • -a – specifies the name of the application to open.

    E.g., open –a “App Store”

  • -b – specifies the bundle identifier of the application to open.

    E.g., open –b com.apple.AppStore

Force close an app

#!/bin/bash 
killall “appname” 

The killall command is used to kill processes running on the system.

Uninstall an app

#!/bin/bash 
sudo rm -rf “/path to the app” 

The rm command removes the directory entries on a Mac system. Somes of the options supported with the command in this respect are –

  • -r – Removes the file hierarchy
  • -f – Removes the files without prompting for confirmation

Device power management

#!/bin/bash 
sudo shutdown -r now 

The shutdown command closes down the system at a given time. Some of the options supported with the command are –

  • -r – The system is rebooted at the given time.
  • -h – The system is halted at the given time.
  • -s – The system is put to sleep at the given time.
  • time – The time at which the system will execute the shutdown command. now indicates immediately. To schedule the action, use the format +number (in minutes) or yymmddhhmm. Example –

    shutdown –r +60 (wait for an hour before shutdown)

    shutdown –r 2109142134 (schedule shutdown on September 14, 21:34:00 2021)

  • warning message – Any other arguments not having a function is passed as the warning message. Example –

    sudo shutdown –r +5 “The system will restart in 5 mins”

Note:

Halt will shut down the system. Sleep will simply turn off the display and lock the device.

Another command to manage power settings is the pmset command. With the power management settings command, we can manage settings like idle sleep timing, wake on administrative access, automatic restart on power loss etc.

sudo pmset sleep 15

This command will set the system sleep timer to 15 minutes i.e., the system will automatically sleep after 15 minutes of inactivity.

sudo pmset displaysleep 15

This command will set the display sleep timer to 15 minutes i.e., the system will turn off the device display after 15 minutes of inactivity.

sudo pmset repeat wakeorpoweron MTWRFSU 9:00:00

This command will wake or power-on the system every day at 9:00 am. Here, MTWRFSU represents the weekdays as –

M – Monday

T – Tuesday

W – Wednesday

R – Thursday

F – Friday

S – Saturday

U – Sunday

sudo pmset repeat shutdown F 20:00:00

This command will shut-down the system every Friday at 8:00 pm.

sudo pmset repeat cancel

This command will cancel all repeating pmset events.

sudo pmset –g

This command will return the system-wide power settings.

Update OS

#!/bin/bash 
getosupd=$(softwareupdate -l | grep "Big Sur" | awk NR==1 | cut -d ' ' -f 3-) 
softwareupdate -i $getosupd 

The above code uses a combination of commands and tools to update the OS to the latest version of macOS Big Sur available.

softwareupdate –l command is used to fetch the list of all available software updates.

grep “Big Sur” scans the list for available versions of macOS Big Sur.

awk NR==1 filters the updated list to the latest version (row number 1).

cut –d ‘ ‘ -f 3- further processes the output to contain only the OS name identifier.

Finally, we pass the OS name identifier as an argument in softwareupdate -i $getosupd to update the OS to the required version. You may replace “Big Sur” in the above code with an OS version name suitable for your use case.

To list all available OS versions for installation, use the following command –

#!/bin/bash  
softwareupdate --list-full-installers | grep 'macOS' | awk '{print ++count " " $0}' 

File management

Open file

#!/bin/bash 
open ‘folder name or filename with extension’ 

The open command can be used to open a file, folder or URL. Some of the ways you can use the command in this respect –

  • open -b com.apple.TextEdit 'path to TextFile.txt' opens the document in the application specified (in this case, TextEdit).
  • open https://www.google.com/ opens the URL in the default browser.

Rename file

#!/bin/bash 
mv ‘path to file/currentFileName’ ‘path to file/newFileName’ 

The mv command is used to move files. Some of the options supported with the command are –

  • -f – Force overwrite on the destination path.
  • -i – Prompt user to confirm file overwrite.

Create a file

touch ‘path to file/filename with extension’

Create a directory

mkdir ‘directoryname’

Delete file/folder

#!/bin/bash 
rm ‘/path to the file or folder’ 

The rm is used to remove directory entries. Some of the options supported with the command are –

  • -r – Recursive deletion for non-empty directory.
  • -d – Attempt to remove the directory and all files.
  • -f – Force attempt delete of all files.
  • -i – Prompt user to confirm deletion of each file.

An example code to recursively delete user files in a directory by prompting users –

rm –ri ‘/path to folder’

The user will be prompted to delete the files one by one. They can confirm with “y” (non-case-sensitive) and decline with “n”.

Delete contents of a folder

#!/bin/bash 
rm ‘/path to the folder/*’ 

Copy a text to clipboard

#!/bin/bash 
echo Content to be copied to clipboard | pbcopy 

This command will copy a given text to the clipboard of the target system.

User management

Create a new user

#!/bin/sh  
# Create a new user with the username New user  
sudo dscl . -create /Users/New\ user 
# Add the display name of the User as John Doe  
sudo dscl . -create /Users/New\ user RealName "John Doe" 
# Replace password_here with your desired password to set the password for this user 
sudo dscl . -passwd /Users/New\ user password_here 
# (Optional)Add a password hint  
sudo dscl . -create /Users/New\ user hint “Password Hint” 
# (Optional)Add a profile picture  
sudo dscl . -create /Users/New\ user picture “/path to picture.png” 
# Set the Unique ID for New user. Replace with a number that is not already taken. 
sudo dscl . -create /Users/New\ user UniqueID 1088 
# Set the group ID for the user 
sudo dscl . -create /Users/New\ user PrimaryGroupID 20 
# Set the shell interpreter to Bash for New\ user  
sudo dscl . -create /Users/New\ user UserShell /bin/bash 
# Create a Home folder for the user 
sudo dscl . -create /Users/New\ user NFSHomeDirectory /Local/Users/New\ user 
# Append the User with admin privilege. If this line is not included the user will be set as standard user.  
sudo dscl . -append /Groups/admin GroupMembership New\ user 
Note:

In Bash, before inserting space while defining file or folder names, we use a backslash \ to separate the characters. This will prevent the shell interpreter from interpreting the space as a separator and assuming they were two different arguments. Hence, we write New user as New\ user in the above code.

dscl is a command line utility for Directory Service. Along with dscl, the create command can be used to create a record.

The . command is an alias for the read command and points to the local directory in the above code.

The passwd command can be used to add password or replace the old password of a user with a new one.

The append command is used to append or create a property (the user in this case) in a given record (the group membership record in this case).

The UniqueID for the user must be unique to the user. 501 is the UniqueID assigned to the first account on the system.

You can set PrimaryGroupID to 80 to add to the admin group directly. Or set the PrimaryGroupID to 20 to add to the standard user group.

Note:

If the system is FileVault encrypted, only enabled users will show up on the initial login screen after reboot. To add the user on the login screen, the user will have to be manually enabled by the device administrator to unlock the disk from System Preferences > Security & Privacy > FileVault > Enable Users.

You can also run the below script to do the same –

sudo fdesetup add -usertoadd New\ user

Return all users

dscl . list /Users 

Return all UniqueID for users

dscl . list /Users UniqueID 

Change password for a user

 sudo dscl . -passwd /Users/New\ user oldpassword newpassword