為什麼 echo “$USER:staff” 會拋出 zsh: bad replacement?

為什麼 echo “$USER:staff” 會拋出 zsh: bad replacement?

感到困惑,因為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

因為:safter$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

相關內容