Skip to content
Advertisement

Customize linux terminal PS1 variable in a function before starting a session

I often start a terminal session to servers from different tabs of my terminal. I would like to create a function that before starting the session it changes the title of the tab so that I can easily recognize which tab has which session open.

Let’s pretend here that my session is an ssh session. When I type in terminal

fn myserver

where fn is a function defined in ~/.bashrc:

function fn() {
  set-title "$1"
  ssh $1         
}
function set-title() {
  if [[ -z "$ORIG" ]]; then
    ORIG=$PS1
  fi
  TITLE="[e]2;$*a]"
  PS1=${ORIG}${TITLE}
}

the terminal starts the session and the title for the tab is changed ONLY AFTER the ssh session ends. I guess that this come because the session is open in the fn function, and only when the function returns is PS1 actualized. How to change the title/update the PS1 variable BEFORE the session begins?

Advertisement

Answer

You are correct; your local host does not display another prompt after you add TITLE to PS1 until after ssh exits. Instead, just output TITLE immediately.

function fn() {
  set-title "$1"
  ssh $1         
}
function set-title() {
  printf 'e]2;%sa' "$1"
}

Note that setting PS1 locally before running ssh has no effect on your prompt on the remote host anyway.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement