Lucas Veiga Lucas Veiga - 22 days ago 5
Bash Question

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.

Answer

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

A solution comes using sed to handle the \ backslash

#!/bin/sh
path=$(echo "$1" | sed 's/\\//g')
touch "$path/test.txt"

so it works in both cases: with or without quotes " and \ in path:

admin@macbookproloreto:~/Developmemt/Pippo Pelo$ ./test.sh "/Users/admin/Developmemt/Pippo\ Pelo"
admin@macbookproloreto:~/Developmemt/Pippo Pelo$ ./test.sh /Users/admin/Developmemt/Pippo\ Pelo