加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-13 18:26:56 所属栏目:Linux 来源:网络整理
导读:如果你能帮助我弄清楚如何确定变量的内容是否以井号开头,我将感激不尽: #!bin/sh myvar="#comment asfasfasdf"if [ myvar = #* ] 这不起作用. 谢谢! JANS 解决方法 一种方法是使用“子串扩展”来切掉变量内容的第一个字符: if [[ ${x:0:1} == '#' ]]then
如果你能帮助我弄清楚如何确定变量的内容是否以井号开头,我将感激不尽:
#!bin/sh    

myvar="#comment asfasfasdf"

if [ myvar = #* ]

这不起作用.

谢谢!

JANS

解决方法

一种方法是使用“子串扩展”来切掉变量内容的第一个字符:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读