I\'m writing a shell script which parses the path of the current working directory (printing a like of all basenames above the current directory).
So far, I\'ve been usi
Another point to note is command substitutions are not generally safe on trailing newlines .
This is obviously fairly contrived, but if you're really concerned about safely
handling input you should be using "$PWD"
. See, for example:
$ my_dir=$'/tmp/trailing_newline\n'
$ mkdir -p "$my_dir"
$ cd "$my_dir"
$ pwd
/tmp/trailing_newline
$ printf "%q\n" "$(pwd)" "$PWD"
/tmp/trailing_newline
$'/tmp/trailing_newline\n'
$ cd "$(pwd)"
sh: cd: /tmp/trailing_newline: No such file or directory
$ cd "$PWD"
It is possible to work around the command substitution but it is by no means pretty. You can append a trailing character and then strip it with a parameter expansion:
$ pwd_guarded="$(pwd; printf '#')"
$ pwd_fixed="${pwd_guarded%$'\n'#}"
$ printf "%q\n" "$pwd_fixed"
$'/tmp/trailing_newline\n'
$ cd "$pwd_fixed"
This is particularly ugly because you then also have to strip the newline that
pwd
adds, which would normally have been stripped by the command substitution.
This becomes a total mess if you don't resort to non-POSIX constructs like
$''
, so basically, just use "$PWD"
if you care about these things. Of course
it is perfectly reasonable to just not support trailing newlines in directory
names.