【问题标题】:Why my default variable is not working in bash script?为什么我的默认变量在 bash 脚本中不起作用?
【发布时间】:2023-01-18 18:05:53
【问题描述】:

这是我的脚本。

alias h='history "${1:-25}"'

我想要的结果是当它像h 100 一样可变时,它显示history 100 的结果并且没有像h 这样的给定输入,它显示像history 25 这样的 25 个元素。

但它仅在我点击 h 时有效,显示 25 个结果,除此之外它给了我参数错误。

-bash: history: too many arguments

我试过 ${1:-25} 但它也返回错误。

-bash: $1: cannot assign in this way

对不起,如果它是重复的,但是 bash 脚本很难查找,因为它有 $ 和数字。

【问题讨论】:

  • 我猜你在你的.bashrc 中这样做?别名不带参数。

标签: bash


【解决方案1】:

别名不能接受参数。它们只在末尾接受参数,而且它们不是位置性的(不能像$1$2 等那样访问)。它相当于:

alias myalias="command opt"
myalias $@  # same as: command opt arg1 arg2 ...

您应该使用 bash 函数,该函数将接收参数并调用 history

function h() {
    x="${1:-25}"
    history $x
}

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2019-05-15
    • 1970-01-01
    • 2022-01-17
    • 2015-05-29
    相关资源
    最近更新 更多