【问题标题】:How to run Bash commands with a PowerShell Core alias?如何使用 PowerShell Core 别名运行 Bash 命令?
【发布时间】:2021-09-07 16:26:50
【问题描述】:

我正在尝试运行 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.

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

【问题讨论】:

  • 我想你想要bash -c history -c
  • @briantist,我们的线在回答时交叉了(你是第一个);从语法上讲,它必须是bash -c 'history -c'(单个-c 参数),但是对于这个特定的命令,它实际上不起作用。我还在答案中添加了有关 Bash 的 CLI 的更多信息。

标签: powershell powershell-core


【解决方案1】:
  • history 是一个 Bash builtin,即只能从 Bash 会话内部调用的 internal 命令;因此,根据定义,您不能直接从 PowerShell 调用它。

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

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

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

然而,即使修复语法问题 - bash -c 'history -c' - 清除 Bash 的历史 - 它似乎 没有效果(并且添加 -i 选项不会' t help) - 我不知道为什么。

解决方法直接删除作为 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

【讨论】:

  • 如您所述, bash -c 'history -c' 不起作用。此外,使用 bash -c 'export test=123' 创建环境变量没有效果。知道为什么吗?在网上找不到替代品。
  • @user9924807,您从 PowerShell(或任何外壳程序,就此而言)运行的任何外部程序都必须在 子进程 中运行。因此,您在该 chid 进程中设置的任何环境变量都仅限于该子进程(及其任何子进程) - PowerShell 永远不会看到它。如果要为当前 PowerShell 会话设置环境变量,请使用 $env:test = '123'
猜你喜欢
  • 2013-04-23
  • 1970-01-01
  • 2016-07-14
  • 2015-01-04
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
相关资源
最近更新 更多