gpt4 book ai didi

Bash 用子 shell 和子字符串进行错误替换

转载 作者:行者123 更新时间:2023-11-29 08:45:24 25 4
gpt4 key购买 nike

一个人为的例子......给出

FOO="/foo/bar/baz"

这有效(在 bash 中)

BAR=$(basename $FOO) # result is BAR="baz"
BAZ=${BAR:0:1} # result is BAZ="b"

这不是

BAZ=${$(basename $FOO):0:1} # result is bad substitution

我的问题是哪个规则导致这个 [subshel​​l substitution] 计算不正确?在 1 跳内完成此操作的正确方法是什么?

最佳答案

首先,请注意,当您这样说时:

BAR=$(basename $FOO) # result is BAR="baz"
BAZ=${BAR:0:1} # result is BAZ="b"

BAZ 结构中的第一位是 BAR 而不是您要获取第一个字符的。因此,即使 bash 允许变量名称包含任意字符,您在第二个表达式中的结果也不会是您想要的。

但是,关于阻止这种情况的规则,请允许我引用 bash 手册页中的内容:

DEFINITIONS
The following definitions are used throughout the rest of this docu‐
ment.
blank A space or tab.
word A sequence of characters considered as a single unit by the
shell. Also known as a token.
name A word consisting only of alphanumeric characters and under‐
scores, and beginning with an alphabetic character or an under‐
score. Also referred to as an identifier.

然后稍后:

PARAMETERS
A parameter is an entity that stores values. It can be a name, a num‐
ber, or one of the special characters listed below under Special Param‐
eters. A variable is a parameter denoted by a name. A variable has a
value and zero or more attributes. Attributes are assigned using the
declare builtin command (see declare below in SHELL BUILTIN COMMANDS).

然后当它定义了你所询问的语法时:

   ${parameter:offset:length}
Substring Expansion. Expands to up to length characters of
parameter starting at the character specified by offset.

所以联机帮助页中阐明的规则说 ${foo:x:y} 构造必须有一个参数作为第一部分,并且参数只能是一个名称,一个数字,或少数特殊参数字符之一。 $(basename $FOO) 不是允许的参数之一。

至于在一次作业中执行此操作的方法,请使用其他响应中提到的其他命令的管道。

关于Bash 用子 shell 和子字符串进行错误替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5917439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com