bashps1

Which command/function for same output of "\w"


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.


Solution

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