为什么 echo “$USER:staff” 会抛出 zsh:错误替换?

为什么 echo “$USER:staff” 会抛出 zsh:错误替换?

感到困惑,因为echo "PATH=$PATH:/usr/local/sbin"没有(认为它与有关:)。

另外,在 Bash 中,这两个命令都按我预期的方式工作。

$ echo "PATH=$PATH"
PATH=/usr/local/bin

$ echo "PATH=$PATH:/usr/local/sbin"
PATH=/usr/local/bin:/usr/local/sbin

$ echo "$USER:staff"
zsh: bad substitution

答案1

因为:s之后$USER被解释为扩展修饰符。如果你执行以下操作,你可以清楚地看到这一点:

% autoload -Uz compinit; compinit       # Init completion system
% zstyle ':completion:*' group-name ''  # Enable completion grouping
% zstyle ':completion:*' format '%d'    # Add titles to the groups
% print $USER: # and press Tab or ^D right after the `:`
modifier
&  -- repeat substitution
A  -- as ':a', then resolve symlinks
P  -- realpath, resolve '..' physically
Q  -- strip quotes
a  -- absolute path, resolve '..' lexically
c  -- PATH search for command
e  -- leave only extension
g  -- globally apply s or &
h  -- head - strip trailing path element
l  -- lower case all words
q  -- quote to escape further substitutions
r  -- root - strip suffix
s  -- substitute string
t  -- tail - strip directories
u  -- upper case all words

从上面的列表中您可以看到,:/它不是一个扩展修饰符。

那么,是否建议始终使用${PATH}${USER}等等……?

不,通常直接使用就可以$USER,但是有时,正如您所见,需要使用${USER}。:)

但是,关于您问题中的代码,我可以为您提供另外两个在 Zsh 中使用的建议:

% print $PATH
/usr/local/bin

% print $path
/usr/local/bin

% path+=/usr/local/sbin  # $path is an array, not a string

% print $PATH            # $path and $PATH are "tied" & automatically in sync
/usr/local/bin:/usr/local/sbin

% print -c $path         # Print the items in columns, like `ls`
/usr/local/bin   /usr/local/sbin

% print -l $path         # Print one item per line, like `ls -l`
/usr/local/bin
/usr/local/sbin

% path+=/usr/local/sbin

% print -c $path       
/usr/local/bin   /usr/local/sbin  /usr/local/sbin

% typeset -U PATH path   # Make each item unique/Eliminate duplicates

% print -c $path       
/usr/local/bin   /usr/local/sbin

相关内容