Lucas Veiga
Lucas Veiga

Reputation: 1795

Bash: Path with \

I'm trying to achieve something really simple here, but something is missing.

I'm trying to create a file via bash script (.sh).

When I try direct on my terminal:

touch /Users/luco/Downloads/My\ Test\ Folder/test.txt

It creates the .txt file without issues. However, when I try directly on my script:

#!/bin/sh
clear
touch "$1"/test.txt

It doesn't work. Gives me this message:

.../test.txt: No such file or directory

I'm calling the script in this ways:

./Script.sh "/Users/luco/Downloads/My\ Test\ Folder/"
./Script.sh /Users/luco/Downloads/My\ Test\ Folder/

None worked.

What am I doing wrong?

Thanks in advance.

Upvotes: 2

Views: 70

Answers (1)

loretoparisi
loretoparisi

Reputation: 16271

Using both quotes and backslashes at invocation time will produce the same error, using either this:

#!/bin/sh
touch "$1/test.txt"

...or this:

#!/bin/sh
touch "$1"/test.txt

The problem can be reproduced as such:

$ ./test.sh "/Users/admin/Developmemt/Pippo\ Pelo"
touch: /Users/admin/Developmemt/Pippo\ Pelo/test.txt: No such file or directory

I get the error (due to the backslash being inside quotes -- "/" -- thus meaning that a literal backslash is expected to be part of the directory name).


By contrast, if not using quotes, the backslash is read as a signal to the shell, not as a part of the directory name, so it works:

$ ./test.sh /Users/admin/Developmemt/Pippo\ Pelo

Upvotes: 3

Related Questions