Shell = 检查变量是否以 # 开头

jan*_*jan 19 linux shell

如果您能帮我弄清楚如何确定变量的内容是否以井号开头,我将不胜感激:

#!bin/sh    

myvar="#comment asfasfasdf"

if [ myvar = #* ] 
Run Code Online (Sandbox Code Playgroud)

这不起作用。

谢谢!

扬斯

Ins*_*yte 21

如果您对哈希进行了转义,您的原始方法就可以正常工作:

$ [[ '#snort' == \#* ]]; echo $?
0
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用“子字符串扩展”切掉变量内容的第一个字符:

if [[ ${x:0:1} == '#' ]]
then
    echo 'yep'
else
    echo 'nope'
fi

yep
Run Code Online (Sandbox Code Playgroud)

从 Bash 手册页:

   ${parameter:offset}
   ${parameter:offset:length}
          Substring  Expansion.   Expands  to  up  to length characters of
          parameter starting at the character  specified  by  offset.   If
          length  is omitted, expands to the substring of parameter start-
          ing at the character specified by offset.  length and offset are
          arithmetic   expressions   (see  ARITHMETIC  EVALUATION  below).
          length must evaluate to a number greater than or equal to  zero.
          If  offset  evaluates  to  a number less than zero, the value is
          used as an offset from the end of the value  of  parameter.   If
          parameter  is  @,  the  result  is  length positional parameters
          beginning at offset.  If parameter is an array name indexed by @
          or  *,  the  result is the length members of the array beginning
          with ${parameter[offset]}.  A negative offset is taken  relative
          to  one  greater  than the maximum index of the specified array.
          Note that a negative offset must be separated from the colon  by
          at  least  one  space to avoid being confused with the :- expan-
          sion.  Substring indexing is zero-based  unless  the  positional
          parameters are used, in which case the indexing starts at 1.
Run Code Online (Sandbox Code Playgroud)

  • 那是 bashism,但标签是关于“shell”而不是“bash”:(。 (4认同)

Kam*_*bus 15

POSIX-compatible version:

[ "${var%${var#?}}"x = '#x' ] && echo yes
Run Code Online (Sandbox Code Playgroud)

or:

[ "${var#\#}"x != "${var}x" ] && echo yes
Run Code Online (Sandbox Code Playgroud)

or:

case "$var" in
    \#*) echo yes ;;
    *) echo no ;;
esac
Run Code Online (Sandbox Code Playgroud)

  • posix 答案+1。在一些基本的计时测试中,“case”方法似乎是相当旧的 32 位 x86 计算机上三种方法中最快的。所有这三个都比一个简单的示例更高效,该示例通过管道传输到分叉的标准输入处理器,例如:`echo $var | 切-c1`。我的分析非常基本,仅基于一台计算机/操作系统上的 10,000,000 次迭代 - YMMV。我只是使用那台较慢的计算机来夸大任何差异并使它们更加明显 - 至少在那个平台上。 (2认同)

Edu*_*nec 6

我知道这可能是异端邪说,但对于这种事情,我宁愿使用 grep 或 egrep 而不是在 shell 中进行。这有点贵(我猜),但对我来说,这个解决方案的可读性抵消了这一点。当然,这是个人品味的问题。

所以:

myvar="   #comment asfasfasdf"
if ! echo $myvar | egrep -q '^ *#'
then
  echo "not a comment"
else
  echo "commented out"
fi
Run Code Online (Sandbox Code Playgroud)

它可以在有或没有前导空格的情况下工作。如果您还想考虑前导标签,请改用 egrep -q '^[ \t]*#' 。