Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to replace home directory with tilde in bash?

Tags:

regex

bash

path

Im trying to work with a path and replace the home directory with a tilde in bash, Im hoping to get it done with as little external programs as necessary. Is there a way to do it with just bash. I got

${PWD/#$HOME/\~} 

But thats not quite right. It needs to convert:

/home/alice to ~ /home/alice/ to ~/ /home/alice/herp to ~/herp /home/alicederp to /home/alicederp 

As a note of interest, heres how the bash source does it when converting the \w value in the prompt:

/* Return a pretty pathname.  If the first part of the pathname is    the same as $HOME, then replace that with `~'.  */ char * polite_directory_format (name)      char *name; {   char *home;   int l;    home = get_string_value ("HOME");   l = home ? strlen (home) : 0;   if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))     {       strncpy (tdir + 1, name + l, sizeof(tdir) - 2);       tdir[0] = '~';       tdir[sizeof(tdir) - 1] = '\0';       return (tdir);     }   else     return (name); } 
like image 433
Jake Avatar asked Apr 05 '12 21:04

Jake


People also ask

Does tilde mean home directory?

~/ (tilde slash)The tilde (~) is a Linux "shortcut" to denote a user's home directory. Thus tilde slash (~/) is the beginning of a path to a file or directory below the user's home directory.

Can I use tilde in Bash script?

Bash also performs tilde expansion on words satisfying the conditions of variable assignments (see Shell Parameters) when they appear as arguments to simple commands. Bash does not do this, except for the declaration commands listed above, when in POSIX mode.

What does tilde mean Bash?

In this article, we learned the meaning of the ~ character and how tilde expansion works in Bash. We use it to refer to a user's home directory, current and previous working directories, and even entries on the directory stack.

What is home directory in Shell?

In the Linux ecosystem, the home directory is also called as the home directory. It is the primary entry point of the user when they are login into the Linux environment. It is responsible to store files, folders, data, and software on /home directory with the respective individual user profile.


1 Answers

I don't know of a way to do it directly as part of a variable substitution, but you can do it as a command:

[[ "$name" =~ ^"$HOME"(/|$) ]] && name="~${name#$HOME}" 

Note that this doesn't do exactly what you asked for: it replaces "/home/alice/" with "~/" rather than "~". This is intentional, since there are places where the trailing slash is significant (e.g. cp -R ~ /backups does something different from cp -R ~/ /backups).

like image 73
Gordon Davisson Avatar answered Sep 23 '22 19:09

Gordon Davisson