Linux   发布时间:2022-04-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了linux – Shell =检查变量是否以#开头大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

如果你能帮助我弄清楚如何确定变量的内容是否以井号开头,我将感激不尽: #!bin/sh myvar="#comment asfasfasdf" if [ myvar = #* ] 这不起作用. 谢谢! JANS 一种方法是使用“子串扩展”来切掉变量内容的第一个字符: if [[ ${x:0:1} == '#' ]] then echo 'yep' else echo '
如果你能帮助我弄清楚如何确定变量的内容是否以井号开头,我将感激不尽:
#!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

大佬总结

以上是大佬教程为你收集整理的linux – Shell =检查变量是否以#开头全部内容,希望文章能够帮你解决linux – Shell =检查变量是否以#开头所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。