Lucas Veiga Lucas Veiga - 1 year ago 89
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:

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:

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

None worked.

What am I doing wrong?

Thanks in advance.

Answer Source

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

touch "$1/test.txt"

...or this:

touch "$1"/test.txt

The problem can be reproduced as such:

$ ./ "/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:

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

A solution comes using sed to handle the \ backslash

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$ ./ "/Users/admin/Developmemt/Pippo\ Pelo"
admin@macbookproloreto:~/Developmemt/Pippo Pelo$ ./ /Users/admin/Developmemt/Pippo\ Pelo
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download