Te whakauru i nga whakahau Linux ki Windows ma te whakamahi i te PowerShell me te WSL

He patai angamaheni mai i nga kaiwhakawhanake Windows: “He aha i kore ai <ВСТАВЬТЕ ТУТ ЛЮБИМУЮ КОМАНДУ LINUX>?. Ahakoa he swipe kaha less taputapu mohio ranei grep ranei sed, Kei te hiahia nga kaihanga Windows ki te uru ngawari ki enei whakahau i roto i a raatau mahi o ia ra.

Pūnaharoto Windows mo Linux (WSL) kua nui te anga whakamua mo tenei kaupapa. Ka taea e koe te karanga i nga whakahau Linux mai i Windows ma te takawaenga i a raatau wsl.exe (РаР ° РїСРРРРјРы, wsl ls). Ahakoa he tino whakapai ake tenei, he maha nga ngoikoretanga ka pa ki tenei whiringa.

  • Te taapiri puta noa wsl hoha me te mea maori.
  • Ko nga ara Windows i roto i nga tautohetohe karekau e mahi i nga wa katoa na te mea ko nga riipene whakamuri te whakamaoritanga hei tohu mawhiti, kaua ko nga kaiwhakawehe whaiaronga.
  • Ko nga ara Windows i roto i nga tautohenga kaore e whakamaoritia ki te waahi maunga e rite ana ki te WSL.
  • Ko nga tautuhinga taunoa e kore e arohia i roto i nga korero WSL me nga ingoa ingoa me nga taurangi taiao.
  • Kaore i te tautokohia te otinga ara Linux.
  • Kaore i te tautokohia te whakaotinga whakahau.
  • Kaore i te tautokohia te whakaotinga tautohetohe.

Ko te mutunga mai, ka kiia nga whakahau Linux hei tangata whenua tuarua i raro i te Matapihi—he uaua ake te whakamahi i nga whakahau taketake. Hei whakataurite i o raatau motika, me whakatika nga raru kua raarangi.

Nga takai mahi PowerShell

Ma nga takai mahi PowerShell, ka taea e tatou te taapiri i te whakaotinga whakahau me te whakakore i te hiahia mo nga prefix wsl, te whakamaori i nga ara Windows ki nga ara WSL. Nga whakaritenga matua mo nga anga:

  • Mo ia whakahau Linux me kotahi te takai mahi me te ingoa kotahi.
  • Me mohio te anga ki nga ara Windows kua paahitia hei tohenga me te huri ki nga ara WSL.
  • Me karanga te anga wsl me te whakahau Linux e tika ana ki tetahi whakauru paipa me te tuku i nga tohenga rarangi whakahau i tukuna ki te mahi.

I te mea ka taea te whakamahi i tenei tauira ki tetahi whakahau, ka taea e tatou te tango i te whakamaramatanga o enei takai me te whakaputa hihiri mai i te rarangi o nga whakahau hei kawemai.

# The commands to import.
$commands = "awk", "emacs", "grep", "head", "less", "ls", "man", "sed", "seq", "ssh", "tail", "vim"
 
# Register a function for each command.
$commands | ForEach-Object { Invoke-Expression @"
Remove-Alias $_ -Force -ErrorAction Ignore
function global:$_() {
    for (`$i = 0; `$i -lt `$args.Count; `$i++) {
        # If a path is absolute with a qualifier (e.g. C:), run it through wslpath to map it to the appropriate mount point.
        if (Split-Path `$args[`$i] -IsAbsolute -ErrorAction Ignore) {
            `$args[`$i] = Format-WslArgument (wsl.exe wslpath (`$args[`$i] -replace "", "/"))
        # If a path is relative, the current working directory will be translated to an appropriate mount point, so just format it.
        } elseif (Test-Path `$args[`$i] -ErrorAction Ignore) {
            `$args[`$i] = Format-WslArgument (`$args[`$i] -replace "", "/")
        }
    }
 
    if (`$input.MoveNext()) {
        `$input.Reset()
        `$input | wsl.exe $_ (`$args -split ' ')
    } else {
        wsl.exe $_ (`$args -split ' ')
    }
}
"@
}

Tuhinga o mua $command ka tautuhi i nga tono kawemai. Na ka hanga hihiri tatou i te takai mahi mo ia o ratou ma te whakamahi i te whakahau Invoke-Expression (ma te tango tuatahi i nga ingoa ingoa ka taupatupatu ki te mahi).

Ka huri te mahi ki runga i nga tautohetohe raina whakahau, ka whakatau i nga ara Windows ma te whakamahi i nga whakahau Split-Path и Test-Pathka huri i enei ara ki nga ara WSL. Ka whakahaerehia e matou nga huarahi ma te mahi kaiawhina Format-WslArgument, ka tautuhia e matou i muri mai. Ka mawhiti i nga tohu motuhake penei i nga mokowhiti me nga reu ka pohehe te whakamaoritanga.

Ka mutu, ka tukuna e matou wsl urunga paipa me etahi tohenga rarangi whakahau.

Ma enei takai ka taea e koe te karanga i o whakahau Linux tino pai ki a koe me te kore e taapiri i te prefix wsl me te kore e manukanuka ki te pehea o nga huarahi ka hurihia:

  • man bash
  • less -i $profile.CurrentUserAllHosts
  • ls -Al C:Windows | less
  • grep -Ein error *.log
  • tail -f *.log

Ko te huinga whakahau taketake e whakaatuhia ana i konei, engari ka taea e koe te hanga anga mo tetahi whakahau Linux ma te taapiri noa ki te raarangi. Mena ka taapirihia e koe tenei waehere ki to tohu PowerShell, ka watea enei whakahau ki a koe i ia wahanga PowerShell, pera i nga whakahau taketake!

Tautuhinga Taunoa

I roto i te Linux, he mea noa ki te tautuhi i nga ingoa ingoa me/ranei nga taurangi taiao i roto i nga korero takiuru, te whakarite i nga tawhā taunoa mo nga whakahau e whakamahia ana (hei tauira, alias ls=ls -AFh ranei export LESS=-i). Ko tetahi o nga ngoikoretanga o te takawaenga ma te anga tauwhitiwhiti kore wsl.exe - kaore i te utaina nga korero, no reira karekau enei whiringa i te waatea (arā. ls i roto i te WSL me wsl ls ka rereke te whanonga me te ingoa ingoa kua tautuhia i runga ake nei).

Ka whakaratohia e PowerShell $PSDefaultParameterValues, he tikanga paerewa mo te tautuhi i nga tawhā taunoa, engari mo nga cmdlet me nga mahi matatau. Ae ra, ka taea e tatou te hanga i nga mahi matatau mai i a tatou anga, engari ka puta mai he raruraru koretake (hei tauira, ko te PowerShell te hono i nga ingoa tawhā wahanga (hei tauira, -a e hono ana ki -ArgumentList), ka taupatupatu ki nga whakahau Linux e tango ana i nga ingoa waahanga hei tohenga), a ko te wetereo mo te tautuhi i nga taunoa kaore e tino tika (te tautuhi i nga tautohenga taunoa me kii te ingoa o te tawhā i roto i te matua, kaua ko te ingoa whakahau anake).

Heoi, me te paku whakarerekētanga ki o tatou anga, ka taea e tatou te whakatinana i tetahi tauira rite ki $PSDefaultParameterValues, ka whakahohe i nga whiringa taunoa mo nga whakahau Linux!

function global:$_() {
    …
 
    `$defaultArgs = ((`$WslDefaultParameterValues.$_ -split ' '), "")[`$WslDefaultParameterValues.Disabled -eq `$true]
    if (`$input.MoveNext()) {
        `$input.Reset()
        `$input | wsl.exe $_ `$defaultArgs (`$args -split ' ')
    } else {
        wsl.exe $_ `$defaultArgs (`$args -split ' ')
    }
}

Te haere $WslDefaultParameterValues ki te raina whakahau, ka tukuna e matou nga tawhā ma wsl.exe. Ko nga mea e whai ake nei e whakaatu ana me pehea te taapiri i nga tohutohu ki to kōtaha PowerShell hei whirihora i nga tautuhinga taunoa. Inaianei ka taea e tatou!

$WslDefaultParameterValues["grep"] = "-E"
$WslDefaultParameterValues["less"] = "-i"
$WslDefaultParameterValues["ls"] = "-AFh --group-directories-first"

I te mea ka whakatauirahia nga tawhā $PSDefaultParameterValueska taea e koe he ngawari ki te whakakore i a raatau mo te wa poto ma te whakauru i te ki "Disabled" ki te tikanga $true. Ko tetahi atu painga o te ripanga hash motuhake ko te kaha ki te mono $WslDefaultParameterValues wehe ke $PSDefaultParameterValues.

Te otinga tohenga

Ka taea e PowerShell te rehita i nga waka tohenga ma te whakamahi i te whakahau Register-ArgumentCompleter. He kaha a Bash taputapu whakaoti-aunoa ka taea te papatono. Ka taea e WSL te waea ki a koe mai i te PowerShell. Mena ka taea e matou te rehita i nga otinga tohenga mo o maatau taputapu mahi PowerShell me te karanga i te bash ki te whakaputa i nga otinga, ka whiwhi tatou i te whakaotinga tohenga me te rite tonu ki te bash ake!

# Register an ArgumentCompleter that shims bash's programmable completion.
Register-ArgumentCompleter -CommandName $commands -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)
 
    # Map the command to the appropriate bash completion function.
    $F = switch ($commandAst.CommandElements[0].Value) {
        {$_ -in "awk", "grep", "head", "less", "ls", "sed", "seq", "tail"} {
            "_longopt"
            break
        }
 
        "man" {
            "_man"
            break
        }
 
        "ssh" {
            "_ssh"
            break
        }
 
        Default {
            "_minimal"
            break
        }
    }
 
    # Populate bash programmable completion variables.
    $COMP_LINE = "`"$commandAst`""
    $COMP_WORDS = "('$($commandAst.CommandElements.Extent.Text -join "' '")')" -replace "''", "'"
    for ($i = 1; $i -lt $commandAst.CommandElements.Count; $i++) {
        $extent = $commandAst.CommandElements[$i].Extent
        if ($cursorPosition -lt $extent.EndColumnNumber) {
            # The cursor is in the middle of a word to complete.
            $previousWord = $commandAst.CommandElements[$i - 1].Extent.Text
            $COMP_CWORD = $i
            break
        } elseif ($cursorPosition -eq $extent.EndColumnNumber) {
            # The cursor is immediately after the current word.
            $previousWord = $extent.Text
            $COMP_CWORD = $i + 1
            break
        } elseif ($cursorPosition -lt $extent.StartColumnNumber) {
            # The cursor is within whitespace between the previous and current words.
            $previousWord = $commandAst.CommandElements[$i - 1].Extent.Text
            $COMP_CWORD = $i
            break
        } elseif ($i -eq $commandAst.CommandElements.Count - 1 -and $cursorPosition -gt $extent.EndColumnNumber) {
            # The cursor is within whitespace at the end of the line.
            $previousWord = $extent.Text
            $COMP_CWORD = $i + 1
            break
        }
    }
 
    # Repopulate bash programmable completion variables for scenarios like '/mnt/c/Program Files'/<TAB> where <TAB> should continue completing the quoted path.
    $currentExtent = $commandAst.CommandElements[$COMP_CWORD].Extent
    $previousExtent = $commandAst.CommandElements[$COMP_CWORD - 1].Extent
    if ($currentExtent.Text -like "/*" -and $currentExtent.StartColumnNumber -eq $previousExtent.EndColumnNumber) {
        $COMP_LINE = $COMP_LINE -replace "$($previousExtent.Text)$($currentExtent.Text)", $wordToComplete
        $COMP_WORDS = $COMP_WORDS -replace "$($previousExtent.Text) '$($currentExtent.Text)'", $wordToComplete
        $previousWord = $commandAst.CommandElements[$COMP_CWORD - 2].Extent.Text
        $COMP_CWORD -= 1
    }
 
    # Build the command to pass to WSL.
    $command = $commandAst.CommandElements[0].Value
    $bashCompletion = ". /usr/share/bash-completion/bash_completion 2> /dev/null"
    $commandCompletion = ". /usr/share/bash-completion/completions/$command 2> /dev/null"
    $COMPINPUT = "COMP_LINE=$COMP_LINE; COMP_WORDS=$COMP_WORDS; COMP_CWORD=$COMP_CWORD; COMP_POINT=$cursorPosition"
    $COMPGEN = "bind `"set completion-ignore-case on`" 2> /dev/null; $F `"$command`" `"$wordToComplete`" `"$previousWord`" 2> /dev/null"
    $COMPREPLY = "IFS=`$'n'; echo `"`${COMPREPLY[*]}`""
    $commandLine = "$bashCompletion; $commandCompletion; $COMPINPUT; $COMPGEN; $COMPREPLY" -split ' '
 
    # Invoke bash completion and return CompletionResults.
    $previousCompletionText = ""
    (wsl.exe $commandLine) -split 'n' |
    Sort-Object -Unique -CaseSensitive |
    ForEach-Object {
        if ($wordToComplete -match "(.*=).*") {
            $completionText = Format-WslArgument ($Matches[1] + $_) $true
            $listItemText = $_
        } else {
            $completionText = Format-WslArgument $_ $true
            $listItemText = $completionText
        }
 
        if ($completionText -eq $previousCompletionText) {
            # Differentiate completions that differ only by case otherwise PowerShell will view them as duplicate.
            $listItemText += ' '
        }
 
        $previousCompletionText = $completionText
        [System.Management.Automation.CompletionResult]::new($completionText, $listItemText, 'ParameterName', $completionText)
    }
}
 
# Helper function to escape characters in arguments passed to WSL that would otherwise be misinterpreted.
function global:Format-WslArgument([string]$arg, [bool]$interactive) {
    if ($interactive -and $arg.Contains(" ")) {
        return "'$arg'"
    } else {
        return ($arg -replace " ", " ") -replace "([()|])", ('$1', '`$1')[$interactive]
    }
}

He iti te ahua o te waehere me te kore e mohio ki etahi o nga mahi o roto o te bash, engari ko ta matou mahi ko tenei:

  • Rēhita ana i te whakaoti tautohenga mo a matou takai mahi katoa ma te tuku rarangi $commands i roto i te tawhā -CommandName ki Register-ArgumentCompleter.
  • Ka whakatakotohia e matou ia whakahau ki te mahi anga e whakamahia ana e te bash mo te whakaoti-aunoa (ki te tautuhi i nga whakaritenga whakaoti-aunoa, whakamahi bash $F, whakapoto mo complete -F <FUNCTION>).
  • Hurihia nga Tohenga PowerShell $wordToComplete, $commandAst и $cursorPosition ki te whakatakotoranga e tumanakohia ana e nga mahi autocompletion a bash e ai ki nga whakaritenga te whakaoti-aunoa ka taea te papatono tukituki.
  • Ka titohia e matou he rarangi whakahau hei whakawhiti ki wsl.exe, ka whakarite kia tika te whakatakotoranga o te taiao, ka karanga i te mahi whakaoti-aunoa e tika ana, me te whakaputa i nga hua i roto i te ahua o te raina.
  • Na ka karanga matou wsl me te raina whakahau, ka wehea e matou te whakaputanga ma nga kaiwhakawehe raina me te whakaputa mo ia CompletionResults, te whakariterite me te mawhiti i nga tohu penei i nga mokowhiti me nga reu ka pohehe te whakamaoritanga.

Ko te mutunga mai, ka whakamahia e a maatau anga whakahau Linux te whakaotinga aunoa rite te bash! Hei tauira:

  • ssh -c <TAB> -J <TAB> -m <TAB> -O <TAB> -o <TAB> -Q <TAB> -w <TAB> -b <TAB>

Ko ia whakaoti-aunoa e tuku uara motuhake ki te tohenga o mua, te panui i nga raraunga whirihoranga penei i nga kaihautu mohio mai i te WSL!

<TAB> ka huri haere i nga tawhā. <Ctrl + пробел> ka whakaatu i nga whiringa katoa e waatea ana.

I tua atu, i te mea kei a maatau te whakaoti aunoa, ka taea e koe te whakaoti aunoa i nga huarahi Linux ki PowerShell!

  • less /etc/<TAB>
  • ls /usr/share/<TAB>
  • vim ~/.bash<TAB>

I nga keehi kaore he hua o te whakaoti-aunoa bash, ka hoki ano a PowerShell ki nga huarahi Windows taunoa. Na, i roto i te mahi, ka taea e koe te whakamahi i nga huarahi e rua i runga i to whakaaro.

mutunga

Ma te whakamahi i te PowerShell me te WSL, ka taea e tatou te whakauru i nga whakahau Linux ki te Matapihi hei tono taketake. Kaore he take ki te rapu mo te hanga Win32, ki nga taputapu Linux ranei, ki te aukati ranei i to rerenga mahi ma te haere ki te anga Linux. Just tāuta WSL, whirihora Kōtaha PowerShell и whakarārangihia ngā whakahau e hiahia ana koe ki te kawemai! Ko te whakaoti-aunoa mo nga tawhā whakahau Linux me Windows me nga ara konae he taumahinga kaore i te waatea i roto i nga whakahau Windows taketake i enei ra.

Ko te katoa o te waehere puna korero i runga ake nei, me etahi atu aratohu mo te whakauru ki roto i to rerenga mahi, kei te waatea konei.

Ko nga whakahau Linux ka kitea e koe he tino whai hua? He aha etahi atu mea noa e ngaro ana i a koe e mahi ana i Windows? Tuhia ki nga korero ranei i runga i GitHub!

Source: will.com

Tāpiri i te kōrero