Replace backslash(“\”) with forward slash(“/”) in a variable in bash

bashbash-scripting

I want to replace backslash(\) with forward slash(/) in a variable in bash.
I tried it like this, but it doesn't work:

home_mf = ${home//(\)//(/)}

For example, I would like

\a\b\c -> /a/b/c

Best Answer

The correct substitution is

home_mf="${home//\\//}"

This breaks up as follows:

  • // replace every
  • \\ backslash
  • / with
  • / slash

Demonstration:

$ t='\a\b\c'; echo "${t//\\//}"
/a/b/c

An alternative that may be easier to read would be to quote the pattern and the replacement:

home_mf="${home//'\'/"/"}"
Related Question