Search code examples
bashterminaltcsh

change terminal title according to the last 2 directories in the path


I want to change the title everytime I enter a new directory ( when using cd ), but show only the last 2 directories. I'm using tcsh at work and bash at home. For example: if I'm at folder ~/work/stuff and I write: cd 1.1, I want my new title to be stuff/1.1.

I already know how to change the title everytime I change the folder:

alias cd 'cd \!*; echo "\033]0;`pwd`\a"'

And I know how to take only the 2 last directories:

pwd | awk -F / -v q="/" '{print $(NF-1)q$NF}'

The question is how to combine these two, or how to do it in a different way? It doesn't have to be through alias to cd.


Solution

  • What I did was creating a script file named titleRename.tcsh with the following code:

    #!/bin/tcsh -f
    
    set fullpath = "`pwd`\a"
    set newTitle = `echo $fullpath | awk -F / '{OFS="/"; if(NF > 2){printf $(NF-2);printf "/"; printf $(NF-1); printf "/"; print $NF;}else print $0}'`
    echo "\033]0;$newTitle"
    

    It splits the pwd with awk, getting only the last 3 directories, and then it prints to the tab name. Then I added in the .alias file the following:

    alias cd    'cd \!*; <dir of script file>/titleRename.tcsh'
    

    Now the title name changes automatically whenever I cd to a different directory :)