为什么以下printf
语句的行为会因...而有所不同? (GNU bash,版本 4.4.18(1)-release (x86_64-pc-linux-gnu))
printf "%s : %s : %s\n" $TERM ${TERM//[^[:alnum:]]/_} ${TERM//[^[:alnum:]]/?}
当处于非特权用户终端会话中时tmux
,输出为:
screen-256color : screen_256color : screen?256color
但是,在终端中root
,对于同一tmux
会话,输出为:
xterm-256color : xterm_256color :
在 之外tmux
,所有用户的输出都是相同的失败:
xterm-256color : xterm_256color :
附加信息:
我只是尝试了相同的命令行,但用星号替换问号,并且发生了相同的失败和成功。这可能是一个与通配符有关的问题吗?该字段应该被视为字符串值,而不是全局值。然后我尝试转义字符并得到以下结果,对于星号普通的六种情况,带有一个反斜杠,以及带有两个反斜杠,对于上面提到的xterm-256color
和情况:screen-256-color
printf "%s : %s : %s\n" $TERM ${TERM//[^[:alnum:]]/_} ${TERM//[^[:alnum:]]/*}
screen-256color : screen_256color : screen*256color
xterm-256color : xterm_256color :
printf "%s : %s : %s\n" $TERM ${TERM//[^[:alnum:]]/_} ${TERM//[^[:alnum:]]/\*}
screen-256color : screen_256color : screen*256color
xterm-256color : xterm_256color :
printf "%s : %s : %s\n" $TERM ${TERM//[^[:alnum:]]/_} ${TERM//[^[:alnum:]]/\\*}
screen-256color : screen_256color : screen\*256color
xterm-256color : xterm_256color : xterm\*256color
答案1
我可以重现:
$ printf "%s : %s : %s\n" $TERM ${TERM//[^[:alnum:]]/_} ${TERM//[^[:alnum:]]/?}
xterm-256color : xterm_256color :
那是因为没有文件匹配图案 xterm?256color
解决方案:
-
$ printf "%s : %s : %s\n" "$TERM" "${TERM//[^[:alnum:]]/_}" "${TERM//[^[:alnum:]]/?}" xterm-256color : xterm_256color : xterm?256color
关闭文件名扩展
$ (set -f; printf "%s : %s : %s\n" $TERM ${TERM//[^[:alnum:]]/_} ${TERM//[^[:alnum:]]/?}) xterm-256color : xterm_256color : xterm?256color
关闭
nullglob
外壳选项$ (shopt -u nullglob; printf "%s : %s : %s\n" $TERM ${TERM//[^[:alnum:]]/_} ${TERM//[^[:alnum:]]/?}) xterm-256color : xterm_256color : xterm?256color