Weekly News Summary for Admins – 2017-04-29

It is vacation time here on Scripting OS X. Updates will be sporadic…

On Scripting OS X

To support Scripting OS X, consider buying one (or both) of my books. Thank you!

If you have already bought and read the books, please leave a review on the iBooks Store. Reviews are important to help new potential readers make the purchase decision. Thank you (again)!

Posts and Opinion

Support and HowTos

To Listen

On bash Environment Variables

This is vacation time with a holiday in the Netherlands. Posting will be more sporadic than usual.

In the previous post we talked about which files you could use to customize your bash environment.

There are (mainly) three customizations you can perform:

This post will look at some useful environment variables.

Choose your own PATH

The PATH environment variable contains a list of directories that bash will search through for commands. You can show your current path by echoing the PATH variable:

$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:

This is the default PATH for a ‘clean’ macOS. Depending on what you have installed, there may be more elements in your PATH. The individual directories are separated by a colon :. When you enter a command, like for example systemsetup at the prompt, bash will search through the directories in PATH in the order until it finds a match.

Note: if there is ever any question on which command is actually executed, you can use the which command to get the effective path to a given command from the shell:

$ which python
/usr/bin/python
$ which systemsetup
/usr/sbin/systemsetup
$ which bash
/bin/bash

You might have installed other (newer versions) of certain tools (such as python or bash itself). Depending on how you install them they may be installed in a way that overrides the tool that is part of macOS. This may lead to problems when scripts assume the system version of a tool.

You can add your own directories by either appending (safe) or prepending (risky) your own directories to the PATH variable:

PATH=$PATH:~/bin
export PATH

This will add the ~/bin directory (which does not exist by default, you have to create and fill your own) to your PATH. The export command tells bash it should export this variable to child processes.

You can add more than one directory to the PATH, either at once, or one per line:

export PATH=$PATH:~/bin:~/Projects/scripts

or

PATH=$PATH:~/bin
PATH=$PATH:~/Projects/scripts
export PATH

Since bash stops looking when it finds a match, the order of the directories in the PATH is important. When you place your directories before the default directories you can override some of the system commands. This can be powerful, but also very dangerous. There are safer methods for overriding system commands. You should add your directory to the end of the PATH to be safe.

Note: the PATH (and other environment variables) are exported to child-shells and scripts executed from the shell. However, not every tool executes directly from a shell, or from a shell with your configuration file. So you should never assume PATH (or any other environment variable) is set to anything specific (or even set) when you write a script. You can either set the PATH at the beginning of a script, or use absolute paths for commands in scripts such as /usr/bin/defaults or /usr/bin/pkgbuild. You can determine the path to a command with the which command.

Prompt Me!

You can also configure the command prompt, i.e. the text that bash displays before you enter a command. By default the macOS prompt looks like this:

hostname:currentDir user$ 

The configuration for the prompt is stored in the PS1 environment variable. You can see the default value by echoing it:

$ echo $PS1
\h:\W \u\$

The letters with the backslash \ in the prompt variable are placeholders that will be replaced with a specific value when the prompt is printed out.

  • \h will be replaced with the hostname of the computer up to the first . (\H would be the complete hostname)
  • \W will be the basename of the current working directory
  • \u is the current user
  • \$ will be $ unless the current user is root or effectively elevated to root privileges, in which case it will be #. This is very useful as a warning when working with elevated privileges.

Since I am the only user on my Mac, and I also know which Mac I am sitting at, I have changed my prompt to something simpler:

export PS1="\W \$ "

Note the space after the \$. If you forget that the cursor will stick right on the $.

(When I log in to a different Mac with ssh the different prompt also reminds me that this shell is on a different Mac.)

You can find a list of escape sequences here.

You can also add color to the prompt data, but the escape sequences will look very messy very quickly. To have the directory name in gray, you use:

export PS1="\[\e[1;30m\]\W\[\e[m\] \\$ "

List in Color

You can also tell bash to color for some other commands, such as ls. To do that you just have to set the CLICOLOR variable:

export CLICOLOR=1

Change the Editor

Some terminal commands will open a text editor directly. For example git may open a text editor so you can enter a commit message. By default the system will open vi but you can change the editor that will be used. There are even some graphical editors that can be used this way. The environment variable for this behavior is EDITOR.

vi or vim:

export EDITOR=vi
export EDITOR=vim

emacs:

export  EDITOR=emacs

nano or pico:

export EDITOR=nano
export EDITOR=pico

TextEdit:

export EDITOR="open -f"

BBEdit:

export EDITOR="bbedit -w --resume"

TextMate:

export EDITOR="mate -w"

SublimeText:

export EDITOR="subl -n -w"

Atom:

export EDITOR="atom --wait"

Note: the -w or --wait argument tells the UI application that there is another process waiting for their output.

Conclusion

Putting all of this together, you can add these lines to your `.bash_profile` or `.bashrc`:

Up Next?

In the next post we will look at bash aliases and functions.

Weekly News Summary for Admins – 2017-04-21

MacAdmins Slack passed 10k users! Congratulations to everyone who has made this possible. This is such a wonderful community. (If you are not yet a member, go join now!)

On Scripting OS X

To support Scripting OS X, consider buying one (or both) of my books. Thank you!

If you have already bought and read the books, please leave a review on the iBooks Store. Reviews are important to help new potential readers make the purchase decision. Thank you (again)!

Updates and Releases

Posts and Opinion

Support and HowTos

To Listen

To Watch

Some Useful AutoPkg Processors

I have updated some of the shared processors in my AutoPkg repository. I find them useful for my AutoPkg workflow and testing recipes. I hope they may be useful for you, too.

You can find more detailed information on the processors in the scriptingosx-recipes repository. To add the repository to your AutoPkg use this command

$ autopkg repo-add scriptingosx-recipes

FileTemplate

This processor can be used to read a file with placeholder variables and write the result to a new file (presumably in the package being built). I use the FileTemplate processor in the FirefoxPrefs.pkg recipe to insert a javascript settings file with the proper values.

String sequences in the template file which are enclosed with % symbols such as %version% or %homepage_url% will be replaced with the value from the autopkg variable. You can use variables defined or obtained in previous recipe steps (e.g. %version% or %NAME%) or add additional values as input variables for the FileTemplate processor (see homepage_url in FirefoxPrefs.pkg)

See the firefox_AA.cfg.template file for an example.

Note: this is a very basic way of setting Firefox preferences. It works great for my use case (supressing update dialogs and setting home page url in student labs). If you need more control over Firefox behavior in your packaging process, look at CCK and use Greg’s FirefoxAutoconfig recipes.

Post Processors

The other processors are designed to be run as post-processors. You can add them to your AutoPkg workflow like this:

$ autopkg run Recipe1.pkg Recipe2.pkg --post com.scriptingosx.processors/Notification

Or with a plist format recipe list.

These are fairly simple post-processors. They can serve as a useful example for how to write and use post-processors.

Notification

This will show a user notification when the processor detects a new download or that a new package was built. (May act strangely when run with no user logged in.)

RevealInFinder

This processor will open a new Finder window and reveal (select) the new file. It will either use a newly archived file, a newly built package or a new download (in that order). (May not work when no user is logged in.)

Archive

When this processor detects a new download or that a new package was built it will copy it to a the directory given in archive_path. archive_path can be on a file server, but it is your responsibility that the share is mounted and available at that path. When the processor determines that a package was built it will copy that, otherwise it will look for a downloaded file. Existing files with the same name will be overwritten.

Even when you don’t copy to a server this can be useful to create an archive of packages outside of the ~/Library/AutoPkg/Caches folder so you can delete cache folders to remove problems with downloads or package building without losing your ‘history’ of packages.

To provide the required archive_path variable you can use the -k/--key argument or a plist format recipe list.

$ autopkg run Recipe1.pkg Recipe2.pkg --post com.scriptingosx.processors/Archive -k archive_path=~/Library/AutoPkg/Archive/ -k archive_subdir=%NAME%

Weekly News Summary for Admins – 2017-04-14

Happy Easter Week-end, everyone!

On Scripting OS X

Updates and Releases

Posts and Opinion

Other News

To Listen

About bash_profile and bashrc on macOS

Note: bash_profile is completely different from configuration profiles. Learn more about Configuration Profiles in my book: ‘Property Lists, Preferences and Profiles for Apple Administrators’

In this spontaneous series on the macOS Terminal I have often mentioned adding something as an alias or function to your bash_profile or bashrc. Obviously, you may wonder: how do I do that? And which file should I use?

Why?

When you work with the command line and the bash shell frequently, you will want to customize the environment. This can mean changing environment variables, such as where the shell looks for commands or how the prompt looks, or adding customized commands.

For example, macOS sets the PATH environment variable to /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin by default. This is a list of directories (separated by a colon ‘:’) that the system searches through in order for commands. I like to add a folder in my home directory ~/bin to that list, so that I can execute certain tools without needing to type out the full path. (e.g. munkipkg, quickpkg and ssh-installer).

In bash you append to existing PATH do this with:

export PATH="$PATH:~/bin"

You could type this command every time you open a new Terminal window (i.e. shell), or you can configure your shell to do this automatically.

Depending on which shell you use and how you start the shell, then certain script files will be executed which allow you to set up these customizations.

This article will talk about customizing bash on macOS. Other shells and other operating systems may have other files or rules.

So, which file?

Thanks to the rich and long history of bash the answer to which file you should put your configuration in, is surprisingly confusing.

There are (mainly) two user level files which bash may run when a bash shell starts. ~/.bash_profile or ~/.bashrc.

Both these files are on the first level of your home directory ~/. Since the file names start with a . Finder and normal ls will not show them. You need to use ls -a to see if they are present. Read more about invisible and hidden files here.

The usual convention is that .bash_profile will be executed at login shells, i.e. interactive shells where you login with your user name and password at the beginning. When you ssh into a remote host, it will ask you for user name and password (or some other authentication) to log in, so it is a login shell.

When you open a terminal application, it does not ask for login. You will just get a command prompt. In other versions of Unix or Linux, this will not run the .bash_profile but a different file .bashrc. The underlying idea is that the .bash_profile should be run only once when you login, and the .bashrc for every new interactive shell.

However, Terminal.app on macOS, does not follow this convention. When Terminal.app opens a new window, it will run .bash_profile. Not, as users familiar with other Unix systems would expect, .bashrc.

Note: The Xterm application installed as part of Xquartz runs .bashrc when a new window opens, not .bash_profile. Other third-party terminal applications on macOS may follow the precedent set by Terminal.app or not.

This is all very confusing.

There are two main approaches:

  • When you are living mostly or exclusively on macOS and the Terminal.app, you can create a .bash_profile, ignore all the special cases and be happy.
  • If you want to have an approach that is more resilient to other terminal applications and might work (at least partly) across Unix/Linux platforms, put your configuration code in .bashrc and source .bashrc from .bash_profile with the following code in .bash_profile:
if [ -r ~/.bashrc ]; then
   source ~/.bashrc
fi

The if [ -r ... ] tests wether a file exists and is readable and the source command reads and evaluates a file in place. Sometimes you see

[ -r ~/.bashrc ] && . ~/.bashrc

(mind the spaces) Which is a shorter way to do the same thing.

Since either file can drastically change your environment, you want to restrict access to just you:

$ chmod 700 ~/.bash_profile
$ chmod 700 ~/.bashrc

That was confusing. Is that all?

No. There are more files which may be executed when a shell is created.

When bash cannot find .bash_profile it will look for .bash_login and if that does not exist either .profile. If .bash_profile is present the succeeding files will be ignored. (though you can source them in your .bash_profile)

There is also a file /etc/profile that is run for interactive login shells (and Terminal.app). This provides a central location to configure the shells for all users on a system. On macOS /etc/profilesets the default PATH with the path_helper tool and then sources /etc/bashrc which (you guessed) would be the central file for all users that is executed for non-login interactive shells. For macOS Terminal.app /etc/bashrc sets the default prompt and then itself sources /etc/bashrc_Apple_Terminal which sets up the session persistence across logins.

So in macOS Terminal.app, before you even see a prompt, these scripts will be run:

  • /etc/profile
    • /etc/bashrc
      • /etc/bashrc_Apple_Terminal
  • if it exists: ~/.bash_profile
    • when ~/.bash_profile does not exists, ~/.bash_login
    • when neither ~/.bash_profile nor ~/.bash_login exist, ~/.profile
  • ~/bash_profile can optionally source ~/.bashrc

There is also a file ~/.inputrc, where you can setup certain command line input options. One common example for this is to enable case-insensitive tab-completion. You can find a list of more options here.

Finally, there is ~/.bash_logout which is run when a shell exits or closes.

Ok, so I have the file, now what?

Whichever file you choose, (I went with option one and have everything in .bash_profile) now you want to put stuff in it.

Technically this is a script, so you can do anything you can code in bash. However, usually the contents of a .bash_profile or .bashrc fall into one of three categories:

  • setting environment variables, usually ones that affect shell behavior (PATH) or look and feel (PS1) or set configuration for other commands or programs (CLICOLOR)
  • aliases
  • functions

I will show some examples for each in the next post(s)!

Terminal Keys and Commands Reference

There have been many posts on Terminal on macOS recently. To catch up, here is a list of all the posts, so far:

And here are a few older posts that also fit well in this topic:

I have a few more ideas and will continue this series as long as I can think of topics. If you have suggestions, please let me know on Twitter, the MacAdmins Slack or in the comments!

And for reading through all of this you get a reward! Download a two-page PDF with all the most important Terminal Keys and Commands! Print it and put them up next to your screen!

You can also download another two-page PDF reference for my book ‘Property Lists, Preferences and Profiles for Apple Administrators’.

Weekly News Summary for Admins – 2017-04-07

On Scripting OS X

Mac Pro: Signs of Life

This week’s big surprise is that Apple has let out some early news that they are working on a new Mac Pro. Even more interesting than new hardware is (for me) that Apple is trying to re-assure the pro and prosumer market that Apple cares about them.

Micheal Tsai has a great summary post.

Other News

To Listen