Er098
Er098

Reputation: 25

Adding a bash command to PS1

I would like to add a bash command into the command prompt. Let's say date -R, to print the current time. How would I go about doing this, while also making sure it doesn't just stick to whatever time comes up when the command is added to PS1? (ergo, when one presses enter on the command line, the prompt updates as well with the new value of the command)

Upvotes: 2

Views: 1984

Answers (2)

chepner
chepner

Reputation: 530843

The shortest way is to include a command substitution, but escaped so that it isn't evaluated until PS1 is displayed.

# PS1="$(date -R) > "  would include the same date in every prompt
PS1='$(date -R) > "

I prefer using the PROMPT_COMMAND variable, which lets you specify code to run prior to displaying each prompt. This lets you break up more complicated prompts into easier-to-follow steps inside an function.

PROMPT_COMMAND='make_prompt'
make_prompt () {
   # Just to demonstrate building up PS1 piece by piece
   PS1="$(date -R)"
   PS1+=" > "
}

For this specific example, though, you don't need a command substitution. There are pre-existing prompt escapes for showing the date:

# duplicating the format of date -R (RFC 2822)
PS1='\D{%a, %d %b %Y %H:%M:%S %z} > '

Inside \D{...}, you can use any string that strftime would handle.

Upvotes: 7

Aplet123
Aplet123

Reputation: 35482

You can use the PROMPT_COMMAND environment variable to run a command before PS1 shows up. For example:

export PROMPT_COMMAND="date -R"

With this in ~/.bashrc, a prompt might look something like:

Wed, 17 Jun 2020 18:15:01 -0400
user@computer:~$

Upvotes: 2

Related Questions