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
  • This belongs on UNIX.SE Dec 28 '17 at 6:47
  • @Dan, why? This is standard Bash, and not platform-specific. May 27 '19 at 8:28

The correct substitution is


This breaks up as follows:

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


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

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


This will do it:

home_mf=${home//\//\\} # forward to backward slash
home_mf=${home//\\//} # backward to forward slash


$ cat slash.sh
set -x
echo $home_mf
echo $home_mf
$ ./slash.sh
+ home=aa/bb/cc
+ home_mf='\aa\bb\cc'
+ echo '\aa\bb\cc'
+ home_mf=/aa/bb/cc
+ echo /aa/bb/cc

The ${variable/..} syntax is ksh, bash, and possibly other shells specific but is not be present in all Bourne shell syntax based shells, e.g. dash. Should you want a portable way (POSIX), you might use sed instead:

home_mf=$(printf "%s" "$home" | sed 's/\//\\/g')    # forward to backward slash
home_mf=$(printf "%s" "$home_mf" | sed 's/\\/\//g') # backward to forward slash
  • doesn't work echo "output: $home_mf" returns "output: homeuser" for "/home/user"
    – Para
    Apr 21 '16 at 7:46
  • 1
    Answer edited to demonstrate it works with me. Not sure what happens in your case, try using printf "%s\n" "$home_mf" instead of echo "$home_mf".
    – jlliagre
    Apr 21 '16 at 8:38
  • Might be an idea to use a different character as separator in the sed s command, e.g. s,/,\\,g and s,\\,/,g. Nov 5 '20 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.