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

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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)