Friday, 18 May 2018

linux - Is it possible to have environment variables in the path of the working directory : PS1?


I am on Lubuntu and I am using bash. My PS1 (in .bashrc) is :


PS1="\w> "

I like it because I need to paste the working directory all the time. The problem is that the path is always very long and since I use terminator I only have half of my screen's width available to display it... it is ugly and annoying. My command prompt looks like that :


/this/is/a/very/long/path/that/i/want/to/make/shorter >

I'd like to set in my environment variables :


$tiavl=/this/is/a/very/long

And then I'll get :


$tiavl/path/that/i/want/to/make/shorter >

The goal is to have something shorter in the command prompt but I still want to be able to copy paste it and do :


cd $tiavl/path/that/i/want/to/make/shorter

It is a bit like with $HOME :


~/path/that/i/want/to/make/shorter  >

I know where I am and I can copy paste the ~.


Thanks.



Answer



You can do this with a little helper function, as below (use /home as an example prefix path):


~ > pwd
/home/me
~ > tiavl=/home
~ > prompt_path () { echo ${1/#$tiavl/\$tiavl}; }
~ > export PS1="\$(prompt_path \w) > "
$tiavl/me >

This uses a simple string manipulation function (see here for lots of examples) in the function to replace the initial part of the path with a literal $tiavl if it matches.


Here's a demo of how to update that function for several paths.


#! /bin/sh

path1=/home
path2=/usr
path3=/var

prompt_path() {
local path
path="${1/#$path1/\$path1}"
path="${path/#$path2/\$path2}"
path="${path/#$path3/\$path3}"
echo "$path"
}

prompt_path $HOME
prompt_path /usr/local
prompt_path /var/tmp

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...