为什么 zsh 不扩展函数“(:a)”中定义的这个 glob

bry*_*unt 7 zsh wildcards assignment

仅当我通过执行 触发全局扩展时,脚本的第二行才有效echo。我不明白为什么。这是命令及其执行情况以提供一些上下文。

函数定义:

~/ cat ~/.zsh/includes/ascii2gif
ascii2gif () {
        setopt extendedglob
        input=$(echo ${1}(:a))
        _path=${input:h}
        input_f=${input:t}
        output_f=${${input_f}:r}.gif
        cd $_path
        nerdctl run --rm -v $_path:/data asciinema/asciicast2gif -s 2 -t solarized-dark $input_f $output_f
}
Run Code Online (Sandbox Code Playgroud)

激活 ascii2gif 函数的函数调试。

~/ typeset -f -t ascii2gif
Run Code Online (Sandbox Code Playgroud)

调试后的函数执行:

~/ ascii2gif ./demo.cast
+ascii2gif:1> input=+ascii2gif:1> echo /Users/b/demo.cast
+ascii2gif:1> input=/Users/b/demo.cast
+ascii2gif:2> _path=/Users/b
+ascii2gif:3> input_f=demo.cast
+ascii2gif:4> output_f=demo.gif
+ascii2gif:5> cd /Users/b
+_direnv_hook:1> trap -- '' SIGINT
+_direnv_hook:2> /Users/b/homebrew/bin//direnv export zsh
+_direnv_hook:2> eval ''
+_direnv_hook:3> trap - SIGINT
+ascii2gif:6> nerdctl run --rm -v /Users/b:/data asciinema/asciicast2gif -s 2 -t solarized-dark demo.cast demo.gif
==> Loading demo.cast...
==> Spawning PhantomJS renderer...
==> Generating frame screenshots...
==> Combining 40 screenshots into GIF file...
==> Done.
Run Code Online (Sandbox Code Playgroud)

我已经尝试了多种变体来尝试强制扩展等input=${~1}(:a),但无济于事。有什么建议么?显然,该脚本可以工作,但似乎不是最佳的。

mur*_*uru 5

这是因为您尝试在此处使用修饰符a方式是用于通配符,并且不会发生通配符(因为通配符通常会导致多个单词,因此它不会发生在需要单个单词的上下文中)。因此,您依赖于命令替换内发生的通配符,然后将结果分配给变量。var=WORD

由于a修饰符可以用于参数扩展,但应用方式不同,您可以尝试:

input=${1:a}
Run Code Online (Sandbox Code Playgroud)

例如:

% cd /tmp
% foo() { input=${1:a}; typeset -p input; }
% foo some-file
typeset -g input=/tmp/some-file
Run Code Online (Sandbox Code Playgroud)