特殊参数查询-多个用于获取命令名称?

特殊参数查询-多个用于获取命令名称?

在我们提供的有关 bash 脚本编写的 uni 文本中,以下变量赋值已被困扰,我还没有得到任何人的答复,因此希望这里有人可以提供帮助。

name=${0##*/}  

这应该扩展以提供输入的命令的名称。我可以看到这是如何从参数 $0 中获取的,因为大括号中的第一个字符是 0。但是,根据上一页(所述 uni 文档)上的信息以及到目前为止我在网上查看的来源, # 表示调用脚本时使用的参数数量,* 包含字符串形式的参数。我只是无法理解所有这些特殊参数如何仅扩展到参数 $0。

我希望该名称扩展为:code/script2 3 3 code/script2 fred george allison。

如果有人能够解释大括号之间的每个特殊参数的作用以扩展为名称:code/script2,我将非常感激

提前感谢您的帮助!

以下是上下文的完整脚本和输出:

1  #!/bin/bash
2  # A simple script showing some of the special variables
3
4 echo "The full name of this script is $0" 
5
6 name=${0##*/}
7
8 echo "The name of this script is $name"
9
10 echo "The process ID of this script is $$"
11
12 echo "This script was called with $# parameters" 13
14 echo "The parameters are \"$*\""
16  echo "Parameter 1 is - $1"
17  echo "Parameter 2 is - $2"
18  echo "Parameter 3 is - $3"

prompt: code/script2 fred george allison
The full name of this script is code/script2 
The name of this script is script2
The process ID of this script is 3501
This script was called with 3 parameters The parameters are "fred george allison"
Parameter 1 is - fred
Parameter 2 is - george
Parameter 3 is - allison 

答案1

你很困惑${#var}(这会返回长度var)${var##substr}返回值var返回after删除最长的前缀匹配 substr

在这种情况下,子字符串是*/调用脚本的名称的所有前导路径组件 - 只留下最终的文件名组件script2.尽管这两个表达式都使用该#字符,但 the 的位置#很重要。

还有${var#substr}一种表面上看起来更接近${#var}但返回的值var但返回删除后最短匹配前缀。

参见示例删除字符串的一部分

相关内容