I am trying to set PS1
so that it prints out something just right after login, but preceded with a newline later.
Suppose export PS1="\h:\W \u\$ "
, so first time (i.e., right after login) you get:
hostname:~ username$
I’ve been trying something like in my ~/.bashrc
:
function __ps1_newline_login {
if [[ -n "${PS1_NEWLINE_LOGIN-}" ]]; then
PS1_NEWLINE_LOGIN=true
else
printf '\n'
fi
}
export PS1="\$(__ps1_newline_login)\h:\W \u\$ “
expecting to get:
# <empty line>
hostname:~ username$
A complete example from the the beginning would be:
hostname:~ username$ ls `# notice: no empty line desired above!`
Desktop Documents
hostname:~ username$
2018 Update (inspired by chepner's answer)
UPDATE: Fixed
PROMPT_COMMAND
issues caused by other answersChanges:
PROMPT_COMMAND
's default behavior (more info below)Enter the following in ~/.bash_profile (substituting first line with your prompt):
PROMPT_COMMAND
I noticed that my tab name in terminal wasn't updating to my current working directory and did some investigating. I realized that above solutions are messing with
PROMPT_COMMAND
. Try this out:PROMPT_COMMAND
in your config files (.bash_profile etc.)INIT_PROMPT_COMMAND="$PROMPT_COMMAND"
to your config fileNow open a new shell:
Notice that when you open a new shell, it runs both a "history check" and updates the name of the tab current working directory. Notice that it only runs the "history check" initially, and then never runs it again.
NOTE: I've only tested this on Mac's Terminal. May be different on other systems.
Running with dogbane's answer, you can make PROMPT_COMMAND "self-destruct", preventing the need to run a function after every command.
In your
.bashrc
or.bash_profile
file, doWhen the file is processed,
PS1
initially does not display a new-line before the prompt. However,PROMPT_CTR
is immediately decremented to -1 (it is implicitly 0 before) before the prompt is shown the first time. After the first command,PROMPT_COMMAND
clears itself and the counter before resetting the prompt to include the new-line. Subsequently, noPROMPT_COMMAND
will execute.Of course, there is a happy medium, where instead of
PROMPT_COMMAND
clearing itself, it just resets to a more ordinary function. Something likeTry the following:
Explanation:
PROMPT_COMMAND
is a special bash variable which is executed every time before the prompt is set.-z
flag to check if the length of a string is 0.