Bash – How to Call a .bashrc Function from a Bash Shell Script

bashfunctiongnome-terminalshell

I want to be able to name a terminal tab so I can keep track of which one is which. I found this function (here) and put it in my .bashrc:

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

and now when I call set-title my new tab name the tab name is changed as expected to "my new tab name". The problem is that I want to open a new tab and name it using set-title. The way I have tried to do this, is like this:

gnome-terminal --geometry=261x25-0+0 --tab -e "bash -c 'set-title tab1; sleep 10'" --tab -e "bash -c 'set-title tab2; sleep 10"

However, now I get the following error message:

bash: set-title: command not found

And I think this is to do with the new gnome tab not knowing about the .bashrc function yet.

How can I get this to work?

Best Answer

Instant of using function set-title you can create command with this functionality, so remove function set-title() that you add from ~/.bashrc and create a file /usr/local/bin/set-title:

#!/bin/bash
echo -ne "\033]0;$1\007"

Add chmod: chmod +x /usr/local/bin/set-title. And after you re-open terminal you can use this command by: set-title TEST (If you have /usr/local/bin/ in your $PATH).

And then you can use it when creating new tab by this way:

gnome-terminal --geometry=261x25-0+0 \
    --tab -e "bash -c 'set-title TAB1; sleep 10'" \
    --tab -e "bash -c 'set-title TAB2; sleep 10'"

If you somehow don't have /usr/local/bin/ in your $PATH, you can try with absolute path to the set-title command:

--tab -e "bash -c '/usr/local/bin/set-title TAB1; sleep 10'"
Related Question