%@ vs. `whoami`

When scripting login events for Mac OS X, there are a number of ways to pull the name of the existing user. The easiest is likely to use the whoami command, which reports back the user name that is currently logged into a system. To do so you can simply run whoami. You can also place `whoami` in scripts where you want the current user to run, unless you have elevated privileges when running the script. For example, when a user logs in, if you want to mount their home directory and it’s on a server called myserver.domain.com then you could use:

mkdir /Volumes/`whoami`
mount_afp ‘afp://server.example.com/Users/`whoami` /Volumes/`whoami`

If you run this with sudo then it would still be run where whomai is expanded as the user. However, if you su your environment, which a number of ways of running certain scripts will do, then you would end up having `whoami` expand as root so it is not recommended to use in all scenarios.

When you are using su you might find that looking at the user(s) with a loginwindow will be a better way to obtain the user the script should possibly be run against even when the user is logged in. There are other ways; one method would be to use ps to look at who is running loginwindow:

ps -Axjc | grep loginwindow | awk ‘{print $1}’

Whoami doesn’t work when you are configuring managed preferences (I guess if you were doing local MCX you could use it to populate data, but it seems a bit annoying to do so). Therefore, you have %@, which expands to be a user’s short name. If, for example, you are configuring mail settings using a managed preference in Workgroup Manager, you can put %@ in place of where a user name goes and each user who that managed preference is applied to will expand the %@ as their user name. If you domain name is @krypted.com, then you could use %@@krypted.com as the email address. Therefore, if I log in as cedgeit would expand to be cedge@krypted.com in the client.

2 Comments

  • kenn
    May 28, 2010 - 10:44 am | Permalink

    How about using logname (instead of whoami)?

    • June 3, 2010 - 2:19 pm | Permalink

      logname totally works as well!

  • Comments are closed.