0

I'm using the command below in a bash terminal (after testing I'll add it to a bash script) to get the absolute path of the current parent folder path. It does add scape characters to the file path and when I echo the variable $DIR it prints out the correct path string.

DIR="$( printf '%q' "$( dirname "$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )")")"

The problem is that after assigning $DIR variable I cannot use it in command substitution. For example using the command cd $DIR or even cd "$DIR" does not work.

If I use the former command I get the error :

bash: cd: too many arguments

However if I use the latter I get the error:

cd: /full/path No such file or directory

Eduardo G
  • 370
  • 4
  • 17
  • 3
    You need to double-quote the variable when you use it. Adding quotes and/or escapes to the variable's value does not work *at all*. See ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) – Gordon Davisson Aug 13 '21 at 10:54
  • @GordonDavisson ok, I'll use double quotes then, but the why the latter form `cd "$DIR` does not work? – Eduardo G Aug 13 '21 at 10:57
  • @EduardoG : What is a _scape character_???? The error message simply means that a directory with the name `/full/path` does not exist. – user1934428 Aug 13 '21 at 11:19
  • @EduardoG : My feeling is that your whole approach is flawed. You want to get the _current parent folder path_ , but I don't understand what you mean with this. Perhaps you could elaborate it with a concrete example. – user1934428 Aug 13 '21 at 11:21
  • 1
    @EduardoG Don't add quotes/escapes to the variable (i.e. remove the`printf '%q'` part, leaving just `DIR="$( dirname "$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )")"`), and use double-quotes when using the variable (`cd "$DIR"`). BTW, why do you do the `cd .. && pwd` in between the two `dirname`s? It'd make more sense to do it after (outside of) both `dirname`s. – Gordon Davisson Aug 13 '21 at 17:56

0 Answers0