2

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

我想清除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 命令?

4

1 回答 1

3
  • history是 Bash内置命令,即只能从 Bash 会话内部调用的内部命令;因此,根据定义,您不能直接从 PowerShell 调用它。

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

    • 不幸的是,从 PowerShell 7.2 开始,清除PowerShell 的Clear-History会话历史记录是不够的,因为它只清除了一个历史记录(PowerShell 自己的),而不是默认情况下用于命令行编辑的模块提供的历史记录- 请参阅此答案PSReadLine

您尝试bash使用命令显式调用 - bash history -c- 在语法上存在缺陷(参见底部)。

但是,即使修复了语法问题 - bash -c 'history -c'- 也无法清除 Bash 的历史 - 它似乎没有任何效果(并且添加该-i选项也无济于事) - 我不知道为什么。

解决方法是直接删除作为Bash (持久)命令历史记录基础的文件

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

要回答帖子标题暗示的一般问题:

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

bash -c 'date +%s'

如果没有-c,第一个参数将被解释为脚本文件的名称或路径。

请注意,第一个参数后面的任何附加-c参数都将成为第一个参数的参数;也就是说,第一个参数充当一个迷你脚本,可以像脚本通常那样接收参数,通过$1,...:

# Note: the second argument, "-", becomes $0 in Bash terms,
#       i.e. the name of the script
PS> bash -c 'echo $0; echo arg count: $#' self one two
self
arg count: 2
于 2021-09-07T16:54:05.903 回答