Shell =检查variables是否以#开头

我会很感激,如果你能帮助我如何弄清楚,如何确定一个variables的内容是以散列符号开始的:

#!bin/sh myvar="#comment asfasfasdf" if [ myvar = #* ] 

这不起作用。

谢谢!

JANS

一种方法是使用“子串扩展”来切断variables内容的第一个字符:

 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. 

编辑:

当然,如果你逃脱了散列,你的原始方法就可以正常工作:

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

POSIX兼容版本:

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

要么:

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

要么:

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

我知道这可能是异端的,但对于这种事情,我宁愿使用grep或egrep,而不是从壳内进行。 这是一个更昂贵(我猜),但对我来说这个解决scheme的可读性抵消了。 当然,这是个人品味的问题。

所以:

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

它有或没有领先的空间。 如果您想要考虑引导标签,请使用egrep -q'^ [\ t] *#'。

这是另一种方式

 # assign to var the value of argument actual invocation var=${1-"#default string"} if [[ "$var" == "#"* ]] then echo "$var starts with a #" fi 

只要复制粘贴内容到一个文件,授予执行权限,并观察它是如何工作的;)。

希望它有帮助!

问候。