0

My current PS1 looks like this:

╭dotfiles
╰(ivan)•

I'd like to add an invisible timestamp to it, so I can select/highlight it with the cursor when I want to see what time a command ran, but not clutter my normal view.

╭dotfiles 10:24:01
╰(ivan)•

Right now I have:

PS1='╭\033[1m\W\033[0m\n╰(\u)• '

Assuming my background color is black, I could use the ANSI color code for black (\033[0;30m) to print the timestamp invisibly:

PS1='╭\033[1m\W\033[0m \033[0;30m\t\033[0m\n╰(\u)• '

But my background is not always black -- I have a couple color-schemes I switch between.

Ideally, I'd like to dynamically grab the background color from the terminal, but is this possible/feasible? Or maybe there's another approach I could take?


Edit

It was rightly pointed out that the ANSI color codes should be enclosed between \[ and \]. So the above settings should actually be:

PS1='╭\[\033[1m\]\W\[\033[0m\]\n╰(\u)• '

and

PS1='╭\[\033[1m\]\W\[\033[0m\] \[\033[0;30m\]\t\[\033[0m\]\n╰(\u)• '
  • 1
    What terminal emulator are you using, and what settings have you made to that? Most terminal emulators swap the foreground and background colors on highlight, so an invisible text (same foreground as background) remains invisible. – egmont Feb 24 '18 at 17:23
  • 1
    On an unrelated note, unprintable characters in PS1 should be enclosed between \[ and \], otherwise you'll encounter weird line editing issues. See the PROMPTING section in bash's manual. – egmont Feb 24 '18 at 17:24
  • You might want to check the output of xtermcontrol --get-bg or the variable $COLORFGBG. They work / are present in some of the terminal emulators. – egmont Feb 24 '18 at 17:25
  • @egmont I'm using gnome-terminal and alacritty. It turns out the highlight was working in tmux, but like you said, outside tmux it's still invisible. Thanks for mentioning \[ and \], I'd forgotten about that, and ran into some broken prompt behavior because of it. I'll update the post to mention that. – ivan Feb 24 '18 at 17:40
  • 1
    I'll just add that you'll need to make sure to get a new command prompt right before running the command, or else you'll run the chance of having a stale timestamp (if you leave a session running for a while and enter a command into it a few minutes or hours later, for example.) – ErikF Feb 24 '18 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.