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

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

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

#!bin/sh    

myvar="#comment asfasfasdf"

if [ myvar = #* ] 

这不起作用。

谢谢!

詹斯

答案1

如果你的原始方法逃脱哈希

$ [[ '#snort' == \#* ]]; echo $?
0

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

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

yep

来自 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.

答案2

POSIX 兼容版本:

[ "${var%${var#?}}"x = '#x' ] && echo yes

或者:

[ "${var#\#}"x != "${var}x" ] && echo yes

或者:

case "$var" in
    \#*) echo yes ;;
    *) echo no ;;
esac

答案3

我知道这可能有点离经叛道,但对于这种事情,我宁愿使用 grep 或 egrep,而不是在 shell 中执行。这有点昂贵(我猜),但对我来说,这个解决方案的可读性弥补了这一点。当然,这只是个人喜好的问题。

所以:

myvar="   #comment asfasfasdf"
if ! echo $myvar | egrep -q '^ *#'
then
  echo "not a comment"
else
  echo "commented out"
fi

带或不带前导空格都可以。如果您还想考虑前导制表符,请使用 egrep -q '^[ \t]*#'。

答案4

这是另一种方法...

# assign to var the value of argument actual invocation
var=${1-"#default string"}

if [[ "$var" == "#"* ]]
then
  echo "$var starts with a #"
fi

只需将内容复制粘贴到文件中,授予执行权限,然后观察其如何工作;)。

希望能帮助到你!

问候。

相关内容