MacOS – Is it possible to replace the username in Terminal with special characters

macosterminal

I found this which seems close to the solution, but it's not quite there.

EDIT: With JavaScript, I know I can just run test.replace(/\w/g, "*"), where test is my username, but I don't know the equivalent for the Terminal.

Best Answer

The hidden username should be the same length as the original username? Like so:

Alices-MacBook:~ *****

Bobs-MacBook:~ ***

The following code snippet should do the job (and, as a bonus, it'll also hide hostname). Add it to your ~/.bash_profile, or wherever you set PS1. (I created a temporary file - test.sh - for testing, and then sourced that file - '. ./test.sh'. If something had gone spectacularly wrong, and I'd made my prompt illegible, I could simply restart the terminal and be back to my old prompt).

PROMPT_COMMAND=__prompt_command

__hide_string()
{
    echo "$1" | sed 's/./\*/g'
}

__prompt_command()
{
    PS1="$(__hide_string $HOSTNAME):\W $(__hide_string $USER)\$"
}

This will replace every character in the username with a "*" (it'll also do it for the hostname, to show function reuse). I consider this to be less than ideal - the function gets called (twice - once for user, once for hostname) every time the prompt is displayed (even though the username hasn't changed): with a bit of hacking it should be possible to amend it so that it only calls the '__hide_string' function when PS1 is set (i.e. at login).

Explanation: the __prompt_command function we've defined sets PS1 every time the prompt is displayed. (This is probably overkill, but keeps things 'dynamic'). PS1 should be familiar; the only new stuff is that '\h' and '\u' are replaced with calls to the __hide_string function (and use $HOSTNAME and $USER as arguments). __hide_string is the fun part: it echoes its argument to sed, which replaces every individual character with a '*'.