【问题标题】:How to understand this "bash" shell command如何理解这个“bash” shell 命令
【发布时间】:2015-11-12 15:29:25
【问题描述】:

命令是:

[ -d $x ] && echo $x | grep "${1:-.*}"

我已经单独运行了,[ -d $x ] && echo $x 只是输出目录名。 ${1:-.*} 是什么意思?

【问题讨论】:

  • 什么外壳?这会很有帮助,因为 bash、c shell 等都以不同的方式运行命令
  • Centos 上的 bash shell
  • 那是Shell Parameter Expansion。您可以在手册中找到它。

标签: bash shell command parameter-expansion


【解决方案1】:

在您引用的脚本中,grep 被调用。它的第一个论点是什么 它将搜索第一个脚本参数$1,如果有的话 已给出,或 .*,如果没有给出参数,则匹配任何内容。

bash 脚本中的"$1""${1}" 被第一个参数替换 该脚本被调用。有时需要处理 字符串一点,可以通过shell参数扩展来完成,如 Etan Reisner 很有帮助地指出。 :- 就是这样一种工具;有 其他几个。

"${1:-.*}" 表示“如果参数 1 未设置或为空(即,没有 参数),然后替换:之后的部分;在这种情况下, .*.

示例脚本pe:

#!/bin/bash
printf 'parameter count = %d\n' $#
printf 'parameter 1 is "%s"\n' "$1"
printf 'parameter 1 is "%s"\n' "${1:-(not given)}"

输出:

$ ./pe 'foo bar'
parameter count = 1
parameter 1 is "foo bar"
parameter 1 is "foo bar"

$ ./pe
parameter count = 0
parameter 1 is ""
parameter 1 is "(not given)"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2012-06-10
    • 2018-02-22
    • 2012-02-11
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多