[英]Change directory to Window's user directory in WSL bash script
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 (eg C:/Users/Frank/).我正在尝试编写一个脚本来自动在 WSL 中安装一些东西,然后将 repo 克隆到 Windows 中的用户主文件夹(例如 C:/Users/Frank/)。
To do this I need to get the Windows username (eg Frank
) to know where to cd
to.为此,我需要获取 Windows 用户名(例如
Frank
)才能知道cd
到哪里。 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.我发现我可以使用
cmd.exe /c '<command>'
执行 Windows 命令行命令,并且命令echo %USERNAME%
输出 Windows 用户的用户名。
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%
.我收到一个错误,我认为它源于 Windows 回车字符
\r
我猜它位于echo %USERNAME%
的 output 的末尾。
The error: ine 3: cd: $'/mnt/c/Users/Frank\r\r\r': No such file or directory
错误:
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?如何删除 output 末尾的所有
\r
字符?
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 .它使用某种字符串格式来删除所有
\r
字符(而不是tr
,我无法在我的测试中工作)改编自 rici's comment here 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.