0

I have a variable with a directory path. If I echo its content it outputs the right path, but if I try to cd it doesn't and it seems to delete the /home/user/ from the path:

[user@project]$ echo $PROJECT_DELIVERY
/home/user/projects/ws/project/delivery/project_name_0.1.0
[user@project]$ cd $PROJECT_DELIVERY
: No such file or directoryuser/projects/ws/project/delivery/project_name_0.1.0

This is the content of printf %s "$PROJECT_DELIVERY" | xxd

[a27503408@ded30325 install]$ printf %s "$PROJECT_DELIVERY" | xxd
0000000: 2f68 6f6d 652f 6132 3735 3033 3430 382f  /home/user/
0000010: 7072 6f6a 6563 7473 2f61 7332 3530 2f41  projects/as250/A
0000020: 5332 3530 5f4d 3135 3533 5f54 4d54 432f  S250_M1553_TMTC/
0000030: 6465 6c69 7665 7279 2f41 5332 3530 5f4d  delivery/AS250_M
0000040: 3135 3533 5f54 4d54 435f 302e 312e 300d  1553_TMTC_0.1.0.

Any idea what could be causing this behavior? I'm using bash 4.1.2(1)

Blasco
  • 264
  • 1
  • 2
  • 11

3 Answers3

3

You have a trailing CR in the directory name. (See the 0d as the final character in the hex dump.)

This also explains why the directory path is overwritten by the error message. Normally you would get

cd /qwerty
-bash: cd: /qwerty: No such file or directory

But you were getting the equivalent of this, where the leading information has been overwritten by the CR and the subsequent error message:

cd /qwerty
: No such file or directory

Try this to demonstrate the point:

echo "$PROJECT_DELIVERY<"

You can remove the trailing \r character with a construct like this

r=$'\r'                                      # Or r=$(printf "\r")
PROJECT_DELIVERY="${PROJECT_DELIVERY%$r}"    # Strip the CR from the end
roaima
  • 107,089
  • 14
  • 139
  • 261
1

As @Kusalananda commented, your variable contains more than meets the - unattentive - eye. See the blank line after your echo output?

Gerard H. Pille
  • 2,350
  • 9
  • 13
0

Indeed there were '\r' and '\n' characters. I removed them with:

VARIABLE="$(echo "$VARIABLE"|tr -d '\n'|tr -d '\r')"
Blasco
  • 264
  • 1
  • 2
  • 11
  • There's no `\n` in your string so you don't need to remove it. But you are still not double-quoting your variables. Use `VARIABLE=$(echo "$VARIABLE"|tr -d '\r')` if you must use `tr`. – roaima Feb 13 '18 at 13:54
  • @roaima why do I need to double quote them? – Blasco Feb 13 '18 at 13:55
  • Because [when to use double quotes with a variable in shell script?](https://unix.stackexchange.com/questions/78002/when-to-use-double-quotes-with-a-variable-in-shell-script) – roaima Feb 13 '18 at 20:28