I am writing a bash script to mount DFS Windows shares via cifs. I have the main part working, but I am having trouble for when I need the user to enter the DFS path as a variable and convert the backslashes to forward slashes.



 FILEPATH="$("$FILE" | sed -e 's/\\/\//gp')"

I had another script that used a command to find a filepath for AD home directories then piped to sed as per the part | sed -e 's/\\/\//gp

However this script above gives me; ./test.sh: line 10: \\edi3\welshch\test: command not found

  • You need to echo the variable to pipe it into the sed command – EnterUserNameHere Oct 18 at 10:39
  • You need to escape the backslashes in your path: FILE='\\\\edi3\\welshch\\test' – Panki Oct 18 at 10:40
  • @EnterUserNameHere when I echo it to pipe it displays it twice – eekfonky Oct 18 at 10:41
  • @Panki I cannot escape the backslashes as they will be entered as the DFS file path by the user as a variable in the final script – eekfonky Oct 18 at 10:42
  • The error you've provided mentions "line 10", but your script is only 6 lines long. Perhaps the "displaying it twice" is due to some part of the script that you've not included in the question? – JigglyNaga Oct 18 at 10:45

Inside the command substitution you have "$FILE" | sed -e 's/\\/\//gp', which the shell expands to (the equivalent of) '\\edi3\welshch\test' | sed -e 's/\\/\//gp'. Since it's a command, the shell goes looking for a file called \\edi3\welshch\test to run.

You probably meant to use echo "$FILE" | sed ... to pass the contents of FILE to sed via the pipe.

Note that even that's not right, some versions of echo will process the backslashes as escape characters, messing things up. You'll need printf "%s\n" "$FILE" | sed ... for it to work in all shells. See: Why is printf better than echo?

Also, note that the default behaviour of sed is to print the line after whatever operations it does. When you use /p on the s/// command, it causes an additional print, so you get the result twice in the output.

That said, since you're using Bash, you could just use the string replacement expansion:

echo "$FILEPATH"

gives the output //edi3/welshch/test


To substitute individual characters, it's simpler to use tr(1):

FILE=$(echo "$FILE" | tr '\\' / )

The variable has to be output (by echo) to sed. Using sed -n to suppress sed output. Edit - don't need sed -n if we omit the sed p flag.



FILEPATH="$(echo "$FILE" | sed 's/\\/\//g')"
  • 1
    The -n counters the p -- why not remove both? You could also save one backslash by using a different delimiter, eg s_\\_/_g. – JigglyNaga Oct 18 at 10:57
  • @JigglyNaga good call, missed that. Post edited. – suspectus Oct 18 at 11:03

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.