1

In Bash PS1 prompt, \w refers to the current working directory. Is there any equivalent using a command (best if it supports DIRTRIM env variable too).

I thought of the pwd command, but if cwd is /home/foo/bar, the value of "\w" should be ~/bar but the output of pwd is /home/foo/bar. It concludes that pwd is not what I want.

sudoer
  • 154
  • 7
  • it doesnt have the same output as "\w". Say, if my $PWD is /home/foo/bar, the value of "\w" should be ~/bar – sudoer Aug 22 '22 at 12:22
  • I will update the question so it is clearer, sorry – sudoer Aug 22 '22 at 12:22
  • Note that if `pwd` (or $PWD for this matter) is `/home/foo/bar`, it refers to the home directory of user _foo_, and the shortcut form would be `~foo/bar` and not `~/bar` - unless you happen to be user _foo_, of course. – user1934428 Aug 22 '22 at 15:13
  • Don't forget to give some feed-back on proposed solutions. – Léa Gris Aug 22 '22 at 22:52

1 Answers1

1

Bash has special parameter expansion operator @P that will do what you want:

#! /usr/bin/env bash

w='\w'
curdir=${w@P}

printf 'Current directory: %s\n' "$curdir"
   ${parameter@operator}
          Parameter transformation.  The expansion is either a transforma‐
          tion  of  the  value of parameter or information about parameter
          itself, depending on the value of operator.  Each operator is  a
          single letter:

          P      The expansion is a string that is the result of expanding
                 the value of parameter as if it were a prompt string (see
                 PROMPTING below).
Léa Gris
  • 17,497
  • 4
  • 32
  • 41