LinuxおよびWindowsのユーザー名に基づくWSL2動的ファイルパス

LinuxおよびWindowsのユーザー名に基づくWSL2動的ファイルパス

私はbashスクリプトを作成し、WSL2のWindowsとLinuxの部分への動的ファイルパスを提供したいと思います。

#!/bin/bash

# Create the workspace
mkdir /mnt/c/Users/FINIX/Documents/Workspace/test/

# Go to the workspace
cd /mnt/c/Users/FINIX/Documents/Workspace/test/

# Create the temp file to store the branches
touch /home/finix/test.txt

# Clone the repo
git clone https://github.com/test/test.git

# Going to the downloaded repo
cd /mnt/c/Users/FINIX/Documents/Workspace/test/TEST/

ユーザー名 finix を Linux 側のマシンと WSL2 の Windows 側のユーザー名に動的に変更したいと思います。

ベストアンサー1

おそらくより良い方法があります。しかし、私が思いついた方法は次のとおりです。

BashでWindowsユーザー名を検索するには:

winuser=$(powershell.exe -c "Write-Host -NoNewLine ([Environment]::UserName)")

その後、これを使用して次のディレクトリを動的に作成できます。

mkdir /mnt/c/Users/${winuser}/Documents/Workspace/test/

Linuxユーザーにとってははるかに簡単です。 @terdonが提案したように、これは次のように簡単です。

touch ${HOME}/test.txt

または、touch /home/${USER}/test.txt

もちろん、Windows側はWindowsホームが常に/mnt/C/Users/username

別の場所にいる場合、ユーザーのWindowsホームディレクトリをインポートするにはPowerShellの注文が必要です。それは次のとおりです。

winhome==$(powershell.exe -c 'Write-Host -NoNewLine $env:userprofile' | xargs -0 wslpath)(答えをくれた@Pankiに感謝します)。

おすすめ記事