$(id -un)
$(stat -f %Su /dev/console)
$(dscl . -read ~ name |awk '{print $2}')
[^ my preferred choices in blue.]
The first two aren't equivalent.
$(id -un), which is my favorite, tells you who YOU are.
$(stat -f%Su /dev/console) tells you who's logged into the GUI.
They're not the same. (Think
ssh. Think
su or
sudo.) Either may be better, depending on which answer you want, but they can give different answers.
Which, come to think of it, is probably what you meant by "depending on circumstances".
The third form depends on the notion that a user's home folder will
always be of the form /Users/$LOGNAME. That's an unwise assumption.
In the meantime, I'll try to get into the habit of using $LOGNAME rather than $USER, now that I know the latter is deprecated. In point of fact, I rarely use either, because I've run into situations where $USER isn't defined (and I never knew about $LOGNAME).
$(id -un) always works.
In a similar vein, I don't trust $TMPDIR. (For example, it's not set when you
ssh into a Leopard or Snow Leopard system.) I replace its first occurrence with
${TMPDIR:=$(getconf DARWIN_USER_TEMP_DIR)}, but even that doesn't work when you
ssh to Tiger. (For Tiger, use
TMPDIR=/var/tmp/folders.$(id -u)/-TMP-/, but you may have to create the folder.) It's already correct when you
ssh to Lion.