6

I want something like this:

"vivek@grishma:~/xxx/yyy/zzz/src$" to be shown as

"vivek@grishma:datasource$" where I would somehow have predefined "datasource" to be an alias for the long path above.

using the alias command as

" alias datasource='~/xxx/yyy/zzz/src'"

is useful for navigation but it does not take out the long path in the prompt.

Is this possible?

PS- I dont want it to be just "vivek@grishma:" as then each time I should run pwd to know my working directory.

Vivek V K
  • 297
  • 3
  • 11
  • 2
    also see http://askubuntu.com/questions/404341/where-can-i-find-a-complete-reference-for-the-ps1-variable – Stormvirux Apr 01 '14 at 14:04
  • @guntbert The link you have suggested "trims" the path and does not "change" it to another name. So I guess this question is very different from the one you have linked – Vivek V K Apr 02 '14 at 09:45

2 Answers2

6

This will do:

PS1='\u@\h:$(
    case $PWD in
       $HOME/xxx/yyy/zzz/src) echo "datasource ;; 
       *) echo "\w" ;; 
    esac
)\$'

That gives you the flexibility to define other special directories as well.

Aliases won't help you here.

To reduce duplication, put all your special dirs in an array, and use that to generate your aliases and also your prompt. Put all this in your ~/.bashrc:

declare -A labels=(
    [$HOME/xxx/yyy/zzz/src]=datasource
    [$HOME/foo/bar]=baz
)
for path in "${!labels[@]}"; do
    alias "${labels[$path]}"="$path"
done
function path_label () {
    local IFS=:
    if [[ ":${!labels[*]}:" == *:"$PWD":* ]]; then
        # we're in a "known" dir
        echo "${labels[$PWD]}"
    else
        return 1
    fi
}
PS1='\u@\h:$( path_label || echo "\w" )\$'
glenn jackman
  • 17,900
  • Thanks a lot. does exactly what I want. Can this be mended to take the alias even if it is part of the path? What I mean is, if I have $HOME/foo/bar/bob can this become baz/bob ??? – Vivek V K Apr 01 '14 at 16:20
  • 1
    in bash, aliases can only be aliases for commands. They cannot be substituted just anywhere, they are only commands. But yes, you can modify that code to just substitute a prefix of $PWD – glenn jackman Apr 01 '14 at 20:16
1

Put the following scripts in your ~/.bashrc

if [ "$(pwd)" == "$HOME/xxx/yyy/zzz/src" ]; then
    PS1='\u@\h:datasource$ '
else
    :
fi

Go to the directory ~/xxx/yyy/zzz/src and to change the prompt

. ~/.bashrc

In other directory, to get back the original prompt again source your ~/.bashrc.

I don't think you need an alias for that. Always you can use an alias like

alias src='. ~/.bashrc'
sourav c.
  • 44,715