Explain Shell

Here’s a good resource for all of those who is trying to learn shell and/or figure out complex commands with lots of parameters and pipes – Explain Shell.

ExplainShell

You just paste the command and hit the “Explain” button, and the site will decompose the command into parts, providing relevant parts from the manual pages.  There are a few examples to try it out on too.

Accessing current username in sudo scripts on CentOS

I got a bit of a puzzle at work today.  I had a script that was executed as another user via sudo, but I wanted to access the original username in the script, to know who was executing it.  Sudoers manual suggest working with “Defaults env_keep“.  Looking into the /etc/sudoers, I noticed that $USERNAME variable was whitelisted (in line #3 below):

Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS"
Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"

So, I tried to use the $USERNAME variable in my script but it was coming up with empty results.  That made me look deeper into default Bash initialization, and I found out that $USERNAME variable setup wasn’t a part of it.  However, $LOGNAME was (in /etc/profile).  I think, so few people actually use it that nobody noticed or bothered about it until now.  Anyway, the solution now was obvious – simply add $LOGNAME variable to the sudo white list.  Appending this line to the above env_keep ones did the job:

Defaults    env_keep += "LOGNAME"

There. In hopes it will help future generations…

P.S.: All that happened on a more or less default installation of CentOS 6.3, but I’m sure other Red Hat based distributions have a similar issue.

P.P.S.: If your script is ALWAYS invoked via sudo, also have a look at $SUDO_UID, $SUDO_GID, and $SUDO_USER variables.

Color builder for 256-color terminal

Color builder for 256-color terminal

With most Linux terminals now supporting 256 colors, a tool like this one is mighty useful in building the escape sequences.  For off-line use, all code is available in GitHub repository, and all logic behind the calculations is explained in this Habrahabr post (albeit, in Russian).