I want pwd to return /path/to/dir in the format /path/to/dir/ with the "/" at the end. Any ideas as to how I can accomplish this?


With bash4.4+, you could redefine pwd as:

pwd() {
  local -
  set -o pipefail
  builtin pwd "$@" | sed '${/\/$/!s|$|/|;}'

That is add a / to the last line of the current working directory if it was not there already (like after cd /) and return the original exit status thanks to the pipefail option (turned on for that function only with local -).

(with zsh, replace local -; set -o pipefail with set -o localoptions -o pipefail).

POSIXly, you could do:

pwd() (
  pwd=$(command pwd "$@" && echo .) || exit
  printf '%s\n' "$pwd"
  • That sort of worked. Every time I now use pwd I also get "bash: local: `-': not a valid identifier" before the path is returned in the next line.
    – E. l4d3
    Oct 5 '17 at 20:35
  • 1
    @E.l4d3, as I said, it's for bash 4.4 or above. You probably have an older version. Then use the POSIX variant. Oct 5 '17 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.