在 Windows 上的當前目錄中,我有以下腳本檔案 simple_script.sh:
#!/bin/bash
echo "hi from simple script"
我希望通過 powershell 命令列在 wsl 上運行這個腳本。
使用該wsl命令,我找不到告訴 wsl 呼叫腳本代碼的方法。
以下命令有效(我認為)
wsl bash -c "echo hi from simple script"
但是,當嘗試將腳本內容加載到變數中并運行它時,它不會按預期作業:
$simple_script = Get-Content ./simple_script.sh
wsl bash -c $simple_script
失敗:
bash: -c: option requires an argument
我嘗試了一些變體。Get-Content與標志一起使用-Raw似乎可以列印字串中的第一個單詞(但不是整個字串)。不包含 '"' 字符的命令有時似乎可以作業。但我還沒有找到一致的方法。
一個類似的問題似乎不能直接與 wsl 一起使用,并且似乎不能運行駐留在 Windows 檔案系統上的腳本檔案。
uj5u.com熱心網友回復:
要運行腳本,wsl您只需呼叫bash
> bash simple_script.sh
hi from simple script
要將其保存在變數中并在or中作為bash腳本運行,無需wslpowershellGet-Content
> $simple_script = bash /mnt/c/Users/user-name/path/to/simple_script.sh
> Write-Output $simple_script
hi from simple script
注意: Powershell 有一個別名映射echo到Write-Output,所以你也可以使用echo
> $simple_script = bash /mnt/c/Users/user-name/path/to/simple_script.sh
> echo $simple_script
hi from simple script
如果這是您最初的目標,您也可以抓取內容。
> Get-Content simple_script.sh
#!/bin/bash
echo "hi from simple script"
> $content = Get-Content .\simple_script.sh
> Write-Output $content
#!/bin/bash
echo "hi from simple script"
uj5u.com熱心網友回復:
作為提醒bash.exe,在另一個答案中使用的 , 現在被認為已棄用(可能在未來的版本中被洗掉)。
實際上有很多方法可以使用wsl命令來實作它。
您的第一次嘗試實際上非常好:
simple_script.sh:
#!/bin/bash
echo "hi from simple script"
電源外殼:
$simple_script = Get-Content ./simple_script.sh
wsl bash -c $simple_script
您看到的錯誤:
bash: -c: option requires an argument
... 在使用 Windows/DOS CRLF 行尾的 Windows 應用程式中編輯 Linux shell 腳本時,經常會看到這種情況。在這里很難“證明”這種情況,但您可以看到Get-Content通過執行以下操作添加 CRLF:
電源外殼:
> $simple_script = Get-Content ./simple_script.sh
> echo $simple_script | wsl -e "hexdump -c"
0000000 # ! / b i n / b a s h \r \n e c h
0000010 o " h i f r o m s i m p l
0000020 e s c r i p t " \r \n e c h o
0000030 H i \r \n
0000034
看到了\r\n嗎?即使腳本檔案本身是在 Linux 中創建的,并且只有\n行結尾。CRLF 正在由 PowerShell 和Get-Content.
您可以通過簡單地不使用來解決此問題-c。這樣腳本檔案本身就會被執行,而不是解釋每一行。這似乎適用于 CRLF 結尾:
電源外殼:
Get-Content ./simple_script.sh | wsl
# or, safer in case your default shell is not bash:
Get-Content ./simple_script.sh | wsl -e bash
# Same thing, but using a variable as in your example:
$simple_script = Get-Content ./simple_script.sh
Write-Output $simple_script | wsl -e bash
您也可以將其翻轉,就像在另一個答案中一樣,以便在WSL 中讀取和執行腳本(同樣,-c出于與上述相同的原因):
WSL 內部:
# Call the default shell, which will read the script,
# process the shebang line, and hand it off to Bash:
wsl ./simple_script.sh
# Or, more efficiently, process the file directly in
# Bash, skipping the first shell invocation entirely:
wsl -e bash ./simple_script.sh
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/472137.html
標籤:重击 电源外壳 windows-subsystem-for-linux wsl-2
上一篇:我無法使用PHP插入的SQL值
