0

I am trying to write a script to automate installing some things in WSL and then cloning a repo to the user's home folder in Windows (e.g. C:/Users/Frank/).

To do this I need to get the Windows username (e.g. Frank) to know where to cd to. I found that I could execute Windows command line commands with cmd.exe /c '<command>' and that the command echo %USERNAME% outputs the Windows user's username.

This is what I've tried so far:

#!/bin/bash
USER_NAME=`cmd.exe /c 'echo %USERNAME%'`
cd /mnt/c/Users/$USER_NAME
pwd

I get an error that I believe stems from the Windows carriage return characters \r which I guess are at the end of the output of echo %USERNAME%.

The error: ine 3: cd: $'/mnt/c/Users/Frank\r\r\r': No such file or directory

How can I remove all of the \r characters at the end of the output?

Frank Matranga
  • 183
  • 1
  • 2
  • 12
  • 2
    first be sure that your script doesn' contain `\r` chars, `cat -vet myScript`, do you see `^M$` at the end of each line, if yes, then `dos2unix myScript` will fix that. If you still get an error, then try `USER_NAME=\`cmd.exe /c 'echo %USERNAME%' | tr -d '\r'\`` , or you may need `tr -d '015'`. Good luck. – shellter Sep 26 '19 at 13:39

1 Answers1

2

Your code, edited:

#!/bin/bash
UNSANITISED_USER_NAME=`cmd.exe /c 'echo %USERNAME%'`
USER_NAME="${UNSANITISED_USER_NAME//$'\r'}"
cd /mnt/c/Users/$USER_NAME
pwd

It uses some sort of string formatting to remove all \r characters (rather than tr, which I couldn't get to work in my testing) adapted from rici's comment here.

IFcoltransG
  • 101
  • 6