3

I'm using read to read a path from a user like so:

read -p "Input the file name: " FilePath

The user now enters this string:

\Supernova\projects\ui\nebula

What can I do to replace \ with /. The result I want is:

/Supernova/projects/ui/nebula 

By the way, the command:

echo $FilePath

outputs the result:

Supernovaprojectsuinebula

I have no idea what's wrong with it.

binghenzq
  • 581

1 Answers1

10

The problem is that read treats backslash in its input as an escape operator (to escape the separators when using read word1 word2 and the newline to allow line continuation).

To do what you want, you need to add the -r switch to read which tells it not to do that backslash processing, and you also need to set $IFS to the empty string so it treats the whole line as the whole word to assign to the variable¹:

IFS= read -rp "Input file name: " FilePath
UnixPath="${FilePath//\\//}"

Additionally, your echo commands needs double quotes around the variable substitution: echo "$FilePath", and anyway in general echo can't be used to output arbitrary data², so:

printf '%s\n' "$FilePath"

¹ with the default value of $IFS, to prevent it from stripping leading and trailing blanks (space and tab) from the input line

² and for echo as well, backslash is or can be treated specially, even in bash depending on the environment or how it was built.

Joseph R.
  • 39,549
  • @ Joseph R. - I get it that echo '\Supernova\projects\ui\nebula' get result is right:/Supernova/projects/ui/nebula. But is it possable to unuse quotes to get: /Supernova/projects/ui/nebula ? Because when I must do this: read -p "Input the file name : " FilePath then: echo $FilePath,but get Supernovaprojectsuinebula in this way. So I can't use single quotes. – binghenzq Nov 06 '13 at 14:34
  • @binghenzq Please see the updated answer. – Joseph R. Nov 06 '13 at 15:01
  • @binghenzq Also, if you don't mind, I took the liberty of editing your question with this new information because I believe it makes the problem clearer. You can always roll back to your earlier version if you find my edits inaccurate. – Joseph R. Nov 06 '13 at 15:05
  • @ Joseph R. - Extremely grateful,It is a Perfect answer. – binghenzq Nov 07 '13 at 04:51
  • @binghenzq Thanks. I'm glad I could help :) – Joseph R. Nov 07 '13 at 22:37