如何使用 PowerShell Core 别名 运行 Bash 命令?

How to run Bash commands with a PowerShell Core alias?

我正在尝试 运行 Bash 命令,其中 PowerShell Core 中存在别名。

我想清除 bash 历史记录。示例代码如下:

# Launch PowerShell core on Linux
pwsh

# Attempt 1
history -c
Get-History: Missing an argument for parameter 'Count'. Specify a parameter of type 'System.Int32' and try again.

# Attempt 2
bash history -c
/usr/bin/bash: history: No such file or directory

# Attempt 3
& "history -c"
&: The term 'history -c' is not recognized as the name of a cmdlet, function, script file, or operable program.

问题似乎与 history 作为 Get-History 的别名有关 - 有没有办法在 PowerShell 核心中使用别名执行 运行 Bash 命令?

  • history 是一个 Bash builtin,即一个 internal 命令可以只能从 Bash session 内部调用;因此,根据定义,您不能从 PowerShell 直接调用它。

  • 在 PowerShell history 是 PowerShell 自己的 Get-History cmdlet 的别名,其中 -c 引用 -Count 参数,它需要一个参数 (要检索的历史条目数)。

    • 不幸的是,Clear-History is not enough to clear PowerShell's session history as of PowerShell 7.2, because it only clear's one history (PowerShell's own), not also the one provided by the PSReadLine module used for command-line editing by default - see this answer

您尝试使用您的命令 - bash history -c 显式调用 bash - 语法错误(见底部)。

然而,即使修复了语法问题 - bash -c 'history -c' - 清除 Bash 的历史 - 它似乎 没有effect(添加 -i 选项没有帮助)- 我不知道为什么。

解决方法删除文件,它是Bash(持久)命令的基础历史直接:

if (Test-Path $HOME\.bash_history) { Remove-Item -Force $HOME\.bash_history }

回答 post 的标题所暗示的一般问题:

要将带有参数的命令传递给 bash 以供执行,将其传递给 bash -c,作为 单个字符串 ;例如:

bash -c 'date +%s'

如果没有 -c,第一个参数将被解释为 脚本文件.

的名称或路径

请注意,第一个 -c 参数之后的任何 附加 参数将成为 第一个 参数的参数;也就是说,第一个参数作为 mini-script 可以像脚本通常那样接收参数,通过 </code>, ...:[=​​31=] <pre><code># Note: the second argument, "-", becomes [=12=] in Bash terms, # i.e. the name of the script PS> bash -c 'echo [=12=]; echo arg count: $#' self one two self arg count: 2