Be yourself, even when you’re root

Ever run a command only to realize you’re not root but need to be? Of course you have. What if that command was long and painful to create? There’s no reason, Dude, to not have access to your bash history even after becoming root vi ‘su’.

function su () {
    local SUUSER=root
    local ORIGU=$USER
    local ORIGG=`groups | awk '{print $1}'`
    if [[ $# -gt 0 ]] ; then
        local char=`echo $1 | cut -c 1`
        if [[ "$char" == '-' ]] ; then
            /bin/su $*
            return $?
            local SUUSER=$1
    #append recent history to the history file
    history -a
    /bin/su ${SUUSER} -c "env USER=${SUUSER} HOME=${HOME} ${SHELL}; \
          [ -f ${HOME}/.ICEauthority ] \
          && chown $ORIGU:$ORIGG ${HOME}/.ICEauthority ${HOME}/.viminfo"
    # Clear the history list by deleting all the entries.
    history -c
    # Read the contents of the history file and use them as the current history.
    history -r

This function honors the ‘su -‘ syntax in case you need it. If you have special permissions on your ~/.ICEauthority or ~/.viminfo, you’ll need to make adjustments obviously. Remember that the backslashes need to be the last characters on the line. They’re only there to make it more readable, so feel free to ditch them in favor of a longer line.

Now when you ‘su’ or even ‘su someotheruser’ you’ll get to keep your own history.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.