Bash参数扩展与函数/别名输出



所以我得到了以下别名:

alias current_dir="pwd | sed -e 's/ /\ /'"

在另一个地方,我首先保护返回的字符串,以便使用参数展开来小写字符串,如下所示:

CURRENT_DIR=$(current_dir)
echo "${CURRENT_DIR,,}"

但我想知道是否有可能直接使用别名/函数调用参数扩展?我尝试了以下几种可能性,但它们都不适合我:

echo "${current_dir,,}"       # just an empty echo
echo "${$(current_dir),,}"    # bad substitution
echo "${"$(current_dir)",,}"  # bad substitution

不,不可能。您必须将输出保存在一个中间变量中。这是不可避免的。

你可以使用

declare -l CURRENT_DIR=$(current_dir)

尽管Shellcheck在同一行中有一些关于declare和命令替换的明智的词语


但是,要获得正确的shell引用/转义版本的字符串,请使用

之一
$ mkdir '/tmp/a dir "with quotes and spaces"'
$ cd !$
$ printf -v CURRENT_DIR "%q" "$PWD"
$ echo "$CURRENT_DIR"
/tmp/a dir "with quotes and spaces"
$ CURRENT_DIR=${PWD@Q}
$ echo "$CURRENT_DIR"
'/tmp/a dir "with quotes and spaces"'

改掉使用全大写变量名的习惯,将它们保留为由壳保留。有一天你会写PATH=something然后想知道为什么你的脚本坏了。


${var@operator}出现在bash 4.4:

${parameter@operator}
Parameter transformation.  The expansion is either a transformation of the
value of parameter or information about parameter itself, depending on the
value of operator.  Each operator is a single letter:
Q      The  expansion is a string that is the value of parameter quoted in
a format that can be reused as input.
E      The expansion is a string that is the value of parameter with back-
slash  escape sequences expanded as with the $'...' quoting mechan-
sim.
P      The expansion is a string that is the result of expanding the value
of parameter as if it were a prompt string (see PROMPTING below).
A      The expansion is a string in the form of an assignment statement or
declare command that, if evaluated, will  recreate  parameter  with
its attributes and value.
a      The  expansion  is  a string consisting of flag values representing
parameter's attributes.
If parameter is @ or *, the operation is applied to each positional param-
eter in turn, and the expansion is the resultant list.  If parameter is an
array variable subscripted with @ or *, the case modification operation is
applied  to  each  member  of  the array in turn, and the expansion is the
resultant list.

最新更新