Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Show HN: Try my new Bash prompt
4 points by kazinator on Aug 4, 2023 | hide | past | favorite | 6 comments

  PS1='\$ ' # short and sweet prompt

  old_cmdno=${old_cmdno-0}
  old_lines=${old_lines-0}
  old_cols=${old_cols-0}

  prepare_terminal()
  {
    stty rows $((LINES - 1))
    printf "\n\033[1A"
    old_lines=$LINES
    old_cols=$COLUMNS
  }

  update_status_line()
  {
    local exit=$?
    local getcmdno='\#'
    local cmdno=${getcmdno@P}
    local esc=$(printf "\033")
    local pwd=$PWD
    local dots=

    [ $LINES -eq $old_lines -a $COLUMNS -eq $old_cols ] || prepare_terminal

    local status_esc="$esc[7m$esc[m"

    while true; do
      [ "${pwd#/*/}" == "$pwd" ] && break
      local status="$esc[7m$(date +%m-%d/%H:%M)$esc[m $HOSTNAME $dots$pwd"
      local status_len=$((${#status} - ${#status_esc}))
      [ $status_len -le $COLUMNS ] && break
      pwd=${pwd#/}
      pwd=/${pwd#*/}
      dots='...'
    done

    status_len=$((${#status} - ${#status_esc}))

    [ $status_len -gt $COLUMNS ] && status=

    printf "${esc}7$esc[%s;1H$esc[K%s$esc[1;%sr${esc}8" $((LINES + 1)) "$status" $LINES
    if [ $exit -ne 0 -a $cmdno -ne $old_cmdno ] ; then
      printf "!%s!\n" $exit
    fi
    old_cmdno=$cmdno
  }

  PROMPT_COMMAND='update_status_line'


Erratum: the break test at the top of the loop body needs to go to the bottom:

  while true; do
    local status="$esc[7m$(date +%m-%d/%H:%M)$esc[m $HOSTNAME $dots$pwd"
    local status_len=$((${#status} - ${#status_esc}))
    [ $status_len -le $COLUMNS ] && break
    pwd=${pwd#/}
    pwd=/${pwd#*/}
    dots='...'
    [ "${pwd#/*/}" == "$pwd" ] && break
  done
This fixes an issue reported by a user on Mastodon: that when you change to a directory like / or /home, the status line disappears.


This is now known as Basta! (BAsh STAtus line).

https://www.kylheku.com/cgit/basta/tree/


bash: !\n: event not found bash: syntax error near unexpected token `fi' bash: syntax error near unexpected token `}' bash: update_status_line: command not found $ printf "!%s!\n" $exit^C bash: update_status_line: command not found $ echo $BASH_VERSION 5.2.15(1)-release


When ! occurs in an interactive command, Bash treats that specially (for history substitution or something; I don't use this so I'm foggy on the details).

It's a POSIX violation which the Bash people think is okay because it doesn't affect scripts.

So you can't just dump this into your shell interactively. It's meant to be put into a file that is sourced.

Sorry about not mentioning it!


Can you add a link to a screenshot?


It was supposed to be a surprise!

I just put one into this Mastodon post:

https://mstdn.ca/@Kazinator/110832579322158690

Direct link to image:

https://cdn.mastdn.ca/media_attachments/files/110/832/577/54...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: