Home > Back-end >  Multiple substring replacement in bash
Multiple substring replacement in bash

Time:02-11

I'm working in an HPC cluster which has a lot of partitions ($HOME, $SCRATCH, $WORKDIR, $SHARED,...) and was trying to find a way to clearly identify which partition I'm at the moment.

After some digging, I found that

export PS1="\e[33;1m\u@\h: \e[31m\w\e[0m\$ "

would show me what I'm looking for. However, the path becomes really cumbersome since all of these partitions have a really long pwd output.

I found out that this command,

aaa@bbb: ~$ echo $PROMPT_COMMAND
printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" ${PWD/#$HOME/~}"

mainly the ${PWD/#$HOME/~} part, might be why the $HOME directory appears simply with ~.

Is there a way to change this environment variable (or any other alternative) for me to have something like:

aaa@bbb: ~/foo/bar$          # when I'm working in $HOME
aaa@bbb: scratch/foo/bar$    # when I'm working in $SCRATCH
aaa@bbb: shared/foo/bar$     # when I'm working in $SHARED

CodePudding user response:

Set PROMPT_COMMAND to command, which will set a variable with truncated path value.

Replace \w in PS1 with the variable name.

My example:

export PROMPT_COMMAND='export CURDIR=$( pwd | sed "s|$HOME|~|;s|/var/lib/postgresql|pg|;s|/opt|stuff|" )'
export PS1='\[\033]0;\u@\h:\w\007\]\[\033[01;32m\]\u@\h\[\033[01;34m\] $CURDIR \$\[\033[00m\] '

CodePudding user response:

In ~/.bashrc you can define :

PROMPT_DIRTRIM=3

to keep the last 3 compoments of $PWD

  • Related