首页 > 解决方案 > 我无法解释这个 tcsh 脚本的功能

问题描述

我试图解释这段tcsh代码:

echo -n '$ '
set x = $<:q
echo $x:q
set x = ( `echo _$x:q | sed 's/\<-/\\-/g;' | tr '[?*' '\r\v\b'` )

但我不知道是什么:q意思。脚本之前没有任何内容声明q. 不<应该发送文件作为输入吗?

标签: tcsh

解决方案


(t)csh 中的变量可以有 -:修饰符;从tcsh手册页:

   The word or words in a history reference can be edited, or
   ``modified'', by following it with one or more modifiers, each preceded
   by a `:':

       h       Remove a trailing pathname component, leaving the head.
       t       Remove all leading pathname components, leaving the tail.
       r       Remove a filename extension `.xxx', leaving the root name.
       e       Remove all but the extension.
       u       Uppercase the first lowercase letter.
       l       Lowercase the first uppercase letter.
       s/l/r/  Substitute l for r.  l is simply a string like r, not a
               regular expression as in the eponymous ed(1) command.  Any
               character may be used as the delimiter in place of `/'; a
               `\' can be used to quote the delimiter inside l and r.  The
               character `&' in the r is replaced by l; `\' also quotes
               `&'.  If l is empty (``''), the l from a previous
               substitution or the s from a previous search or event
               number in event specification is used.  The trailing
               delimiter may be omitted if it is immediately followed by a
               newline.
       &       Repeat the previous substitution.
       g       Apply the following modifier once to each word.
       a (+)   Apply the following modifier as many times as possible to a
               single word.  `a' and `g' can be used together to apply a
               modifier globally.  With the `s' modifier, only the
               patterns contained in the original word are substituted,
               not patterns that contain any substitution result.
       p       Print the new command line but do not execute it.
       q       Quote the substituted words, preventing further
               substitutions.
       Q       Same as q but in addition preserve empty variables as a
               string containing a NUL.  This is useful to preserve
               positional arguments for example:

                   > set args=('arg 1' '' 'arg 3')
                   > tcsh -f -c 'echo ${#argv}' $args:gQ
                   3
       x       Like q, but break into words at blanks, tabs and newlines.

因此:q修饰符用于“引用替换的单词,防止进一步替换”。

这对于防止通配最有用(这就是“替换”的含义,尽管还有一些其他类型,例如历史替换):

> set x = "star: *"

> echo $x:q
star: *

> echo "$x"
star: *

> echo $x
star: bin boot data dev etc home lib lib32 lib64 lost+found media mnt nix opt proc root run sbin sys tmp usr var

如您所见,您也可以使用引号;:q虽然在某些情况下更有用/更易读。


推荐阅读