bash - shell中 "${0##*[\\/]}"是什么意思?

标签 bash parameter-expansion

我在查看其他人的 shell 脚本时遇到了问题。

我看到声明了

APP_NAME="${0##*[\\/]}"

既然找不到答案,请问这段代码是什么意思?

最佳答案

Shell Parameter Expansion获取脚本名称本身,没有路径

参见 bash手册:

${parameter##word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching).

If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted.

Pattern Matching :

*

Matches any string, including the null string. When the globstar shell option is enabled, and ‘*’ is used in a filename expansion context

[…]

Matches any one of the enclosed characters.

说明

${parameter<...>} expression表示可以扩展shell参数。

${1:-"default_arg_value"}将扩展为 "default_arg_value"如果脚本在没有参数的情况下运行。

0 - 是第 0 个参数,即脚本名称本身

${0##<pattern>}将删除与 <pattern> 最长的匹配的一部分 $0

*[\\/]表示以 \ 结尾的任何字符串或 /符号。

所以,APP_NAME="${0##*[\\/]}"意味着 $APP_NAME将由脚本名称本身初始化,没有路径。

示例

假设您有脚本 a/b/c/d/test.sh :

#!/bin/bash
echo "${0##*[\/]}"
echo "${1#*[\/]}"
echo "${2##[\/]}"
$ bash a/b/c/d/test.sh /tmp/e /tmp/ff
> test.sh
> tmp/e
> tmp/ff

关于bash - shell中 "${0##*[\\/]}"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57967131/

相关文章:

python - 无法在容器内启动 selenium 测试,WebDriverException :Chrome failed to start: exited abnormally

java - 从java调用时bash脚本不等待命令完成

Linux 按列合并两个文件

bash - 如何使用带参数的字符串来调用脚本,就像 bash 在解释命令行时所做的那样?

bash - 在bash中,将字符串的每个字符替换为固定字符 ("blank out"一个字符串)

bash 参数扩展和组合模式匹配运算符

linux - 用awk解析多行

linux - 使用 -C(或 -B/-A)运行时在 grep 结果之间输出空行

bash - 如何记住哪个扩展 ${var%} ${var#} 从哪一端开始工作?

environment-variables - 附加到csh中可能尚不存在的环境变量的简单方法