1167

I would like to check if a string begins with "node" e.g. "node001". Something like

if [ $HOST == node* ]
  then
  echo yes
fi

How can I do it correctly?


I further need to combine expressions to check if HOST is either "user1" or begins with "node":

if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi

> > > -bash: [: too many arguments

How can I do it correctly?

1
  • 7
    Don't be too tempted to combine expressions. It may look uglier to have two separate conditionals, though you can give better error messages and make your script easier to debug. Also I would avoid the bash features. The switch is the way to go.
    – hendry
    Commented Jan 31, 2010 at 17:02

13 Answers 13

1564

This snippet on the Advanced Bash Scripting Guide says:

# The == comparison operator behaves differently within a double-brackets
# test than within single brackets.

[[ $a == z* ]]   # True if $a starts with a "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

So you had it nearly correct; you needed double brackets, not single brackets.


With regards to your second question, you can write it this way:

HOST=user1
if  [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes1
fi

HOST=node001
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes2
fi

Which will echo

yes1
yes2

Bash's if syntax is hard to get used to (IMO).

20
  • 24
    For regex do you mean [[ $a =~ ^z.* ]] ?
    – JStrahl
    Commented Mar 18, 2013 at 7:13
  • 4
    So is there a functional difference between [[ $a == z* ]] and [[ $a == "z*" ]]? In other words: do they work differently? And what specifically do you mean when you say "$a is equal to z*"?
    – Niels Bom
    Commented Jun 16, 2015 at 10:37
  • 9
    You don't need the statement separator ";" if you put "then" on its own line
    – Yaza
    Commented Oct 14, 2015 at 11:45
  • 16
    Just for completeness: To check if a string ENDS with ... : [[ $a == *com ]]
    – lepe
    Commented Feb 6, 2017 at 2:56
  • 8
    The ABS is an unfortunate choice of references -- it's very much the W3Schools of bash, full of outdated content and bad-practice examples; the freenode #bash channel has been trying to discourage its use at least since 2008. Any chance of repointing at BashFAQ #31? (I'd also have suggested the Bash-Hackers' wiki, but it's been down for a bit now). Commented Oct 21, 2017 at 23:19
384

If you're using a recent version of Bash (v3+), I suggest the Bash regex comparison operator =~, for example,

if [[ "$HOST" =~ ^user.* ]]; then
    echo "yes"
fi

To match this or that in a regex, use |, for example,

if [[ "$HOST" =~ ^user.*|^host1 ]]; then
    echo "yes"
fi

Note - this is 'proper' regular expression syntax.

  • user* means use and zero-or-more occurrences of r, so use and userrrr will match.
  • user.* means user and zero-or-more occurrences of any character, so user1, userX will match.
  • ^user.* means match the pattern user.* at the begin of $HOST.

If you're not familiar with regular expression syntax, try referring to this resource.

Note that the Bash =~ operator only does regular expression matching when the right hand side is UNQUOTED. If you do quote the right hand side, "any part of the pattern may be quoted to force it to be matched as a string.". You should not quote the right hand side even when doing parameter expansion.

3
  • Thanks, Brabster! I added to the original post a new question about how to combine expressions in if cluase.
    – Tim
    Commented Jan 31, 2010 at 16:44
  • 3
    Its a pity that the accepted answer does not says anything about the syntax of regular expression.
    – CarlosRos
    Commented Apr 26, 2017 at 18:08
  • 68
    FYI the Bash =~ operator only does regular expression matching when the right hand side is UNQUOTED. If you do quote the right hand side "Any part of the pattern may be quoted to force it to be matched as a string." (1.) make sure to always put the regular expressions on the right un-quoted and (2.) if you store your regular expression in a variable, make sure to NOT quote the right hand side when you do parameter expansion. Commented Feb 15, 2018 at 16:34
283

I always try to stick with POSIX sh instead of using Bash extensions, since one of the major points of scripting is portability (besides connecting programs, not replacing them).

In sh, there is an easy way to check for an "is-prefix" condition.

case $HOST in node*)
    # Your code here
esac

Given how old, arcane and crufty sh is (and Bash is not the cure: It's more complicated, less consistent and less portable), I'd like to point out a very nice functional aspect: While some syntax elements like case are built-in, the resulting constructs are no different than any other job. They can be composed in the same way:

if case $HOST in node*) true;; *) false;; esac; then
    # Your code here
fi

Or even shorter

if case $HOST in node*) ;; *) false;; esac; then
    # Your code here
fi

Or even shorter (just to present ! as a language element -- but this is bad style now)

if ! case $HOST in node*) false;; esac; then
    # Your code here
fi

If you like being explicit, build your own language element:

beginswith() { case $2 in "$1"*) true;; *) false;; esac; }

Isn't this actually quite nice?

if beginswith node "$HOST"; then
    # Your code here
fi

And since sh is basically only jobs and string-lists (and internally processes, out of which jobs are composed), we can now even do some light functional programming:

beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
checkresult() { if [ $? = 0 ]; then echo TRUE; else echo FALSE; fi; }

all() {
    test=$1; shift
    for i in "$@"; do
        $test "$i" || return
    done
}

all "beginswith x" x xy xyz ; checkresult  # Prints TRUE
all "beginswith x" x xy abc ; checkresult  # Prints FALSE

This is elegant. Not that I'd advocate using sh for anything serious -- it breaks all too quickly on real world requirements (no lambdas, so we must use strings. But nesting function calls with strings is not possible, pipes are not possible, etc.)

11
  • 28
    +1 Not only is this portable, it's also readable, idiomatic, and elegant (for shell script). It also extends naturally to multiple patterns; case $HOST in user01 | node* ) ...
    – tripleee
    Commented Sep 6, 2013 at 7:12
  • Is there a name for this type of code formatting? if case $HOST in node*) true;; *) false;; esac; then I've seen it here and there, to my eye it looks kinda scrunched up.
    – Niels Bom
    Commented Jun 16, 2015 at 10:28
  • @NielsBom I don't know what exactly you mean by formatting, but my point was that shell code is very much composable. Becaues case commands are commands, they can go inside if ... then.
    – Jo So
    Commented Jun 16, 2015 at 16:58
  • 1
    I know about when to use quotes in case statements now. unix.stackexchange.com/a/68748/150246 . May I ask why in your function beginswith, you can write true and false without echo. And they can be caught by the callers. I am trying to understand this syntax. Thank you.
    – midnite
    Commented Apr 13, 2022 at 19:21
  • 1
    Somehow from this comment I understand now. They are essentially the exit statuses, which are the last command in the function. A single true statement equals to return 0, while false equals to return 1. As these are exit statuses, they cannot be captured by variable assignment, nor by echo, etc. Yet they are cool for places which check the exit status, such as if and boolean expressions. Just want to quote three ways for func.
    – midnite
    Commented Apr 13, 2022 at 20:02
120

You can select just the part of the string you want to check:

if [ "${HOST:0:4}" = user ]

For your follow-up question, you could use an OR:

if [[ "$HOST" == user1 || "$HOST" == node* ]]
6
  • 9
    You should doublequote ${HOST:0:4}
    – Jo So
    Commented Nov 2, 2013 at 23:28
  • @Jo So: What is the reason? Commented Jan 1, 2020 at 13:03
  • 1
    @PeterMortensen, try HOST='a b'; if [ ${HOST:0:4} = user ] ; then echo YES ; fi
    – Jo So
    Commented Jan 5, 2020 at 1:18
  • Alternatively, double brackets: if [[ ${HOST:0:4} = user ]]
    – Zim
    Commented Dec 18, 2020 at 0:55
  • @martin clayton Please post the whole if expression. Commented Mar 10, 2022 at 4:54
65

I prefer the other methods already posted, but some people like to use:

case "$HOST" in 
    user1|node*) 
            echo "yes";;
        *)
            echo "no";;
esac

Edit:

I've added your alternates to the case statement above

In your edited version you have too many brackets. It should look like this:

if [[ $HOST == user1 || $HOST == node* ]];
4
  • Thanks, Dennis! I added to the original post a new question about how to combine expressions in if cluase.
    – Tim
    Commented Jan 31, 2010 at 16:45
  • 13
    "some people like..." : this one is more portable across versions and shells.
    – carlosayam
    Commented Oct 17, 2011 at 5:44
  • With case statements you can leave away the quotes around the variable since no word splitting occurs. I know it's pointless and inconsistent but I do like to leave away the quotes there to make it locally more visually appealing.
    – Jo So
    Commented Nov 6, 2014 at 15:12
  • And in my case, I had to leave away the quotes before ): "/*") did not work, /*) did. (I'm looking for strings starting with /, i.e., absolute paths) Commented Feb 18, 2017 at 20:43
48

While I find most answers here quite correct, many of them contain unnecessary Bashisms. POSIX parameter expansion gives you all you need:

[ "${host#user}" != "${host}" ]

and

[ "${host#node}" != "${host}" ]

${var#expr} strips the smallest prefix matching expr from ${var} and returns that. Hence if ${host} does not start with user (node), ${host#user} (${host#node}) is the same as ${host}.

expr allows fnmatch() wildcards, thus ${host#node??} and friends also work.

2
  • 5
    I'd argue that the bashism [[ $host == user* ]] might be necessary, since it's far more readable than [ "${host#user}" != "${host}" ]. As such granted that you control the environment where the script is executed (target the latest versions of bash), the former is preferable.
    – x-yuri
    Commented Oct 24, 2018 at 21:48
  • 3
    @x-yuri Frankly, I'd simply pack this away into a has_prefix() function and never look at it again.
    – dhke
    Commented Oct 25, 2018 at 10:29
40

Since # has a meaning in Bash, I got to the following solution.

In addition I like better to pack strings with "" to overcome spaces, etc.

A="#sdfs"
if [[ "$A" == "#"* ]];then
    echo "Skip comment line"
fi
4
  • thanks, I was also wondering how to match a string starting with blah:, looks like this is the answer!
    – Anentropic
    Commented Sep 28, 2015 at 13:38
  • 1
    case $A in "#"*) echo "Skip comment line";; esac is both shorter and more portable.
    – tripleee
    Commented Feb 17, 2021 at 9:06
  • is this a reply to the question? I dont see any sdfs... Commented Mar 10, 2022 at 4:52
  • KansaiRobot, it demonstrates how to use * in cash string compare. everyone should replade "sdfs" with the string he wants to compare
    – ozma
    Commented Mar 13, 2022 at 7:58
16

Adding a tiny bit more syntax detail to Mark Rushakoff's highest rank answer.

The expression

$HOST == node*

Can also be written as

$HOST == "node"*

The effect is the same. Just make sure the wildcard is outside the quoted text. If the wildcard is inside the quotes it will be interpreted literally (i.e. not as a wildcard).

15

Keep it simple

word="appel"

if [[ $word = a* ]]
then
  echo "Starts with a"
else
  echo "No match"
fi
9

@OP, for both your questions you can use case/esac:

string="node001"
case "$string" in
  node*) echo "found";;
  * ) echo "no node";;
esac

Second question

case "$HOST" in
 node*) echo "ok";;
 user) echo "ok";;
esac

case "$HOST" in
 node*|user) echo "ok";;
esac

Or Bash 4.0

case "$HOST" in
 user) ;&
 node*) echo "ok";;
esac
1
  • Note that ;& is only available in Bash >= 4. Commented Feb 1, 2010 at 12:00
6
if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi

doesn't work, because all of [, [[, and test recognize the same nonrecursive grammar. See section CONDITIONAL EXPRESSIONS on your Bash man page.

As an aside, the SUSv3 says

The KornShell-derived conditional command (double bracket [[]]) was removed from the shell command language description in an early proposal. Objections were raised that the real problem is misuse of the test command ([), and putting it into the shell is the wrong way to fix the problem. Instead, proper documentation and a new shell reserved word (!) are sufficient.

Tests that require multiple test operations can be done at the shell level using individual invocations of the test command and shell logicals, rather than using the error-prone -o flag of test.

You'd need to write it this way, but test doesn't support it:

if [ $HOST == user1 -o $HOST == node* ];
then
echo yes
fi

test uses = for string equality, and more importantly it doesn't support pattern matching.

case / esac has good support for pattern matching:

case $HOST in
user1|node*) echo yes ;;
esac

It has the added benefit that it doesn't depend on Bash, and the syntax is portable. From the Single Unix Specification, The Shell Command Language:

case word in
    [(]pattern1) compound-list;;
    [[(]pattern[ | pattern] ... ) compound-list;;] ...
    [[(]pattern[ | pattern] ... ) compound-list]
esac
2
  • 1
    [ and test are Bash builtins as well as external programs. Try type -a [. Commented Feb 1, 2010 at 12:05
  • Many thanks for explaining the problems with the "compound or", @just somebody - was looking precisely for something like that! Cheers! PS note (unrelated to OP): if [ -z $aa -or -z $bb ] ; ... gives "bash: [: -or: binary operator expected" ; however if [ -z "$aa" -o -z "$bb" ] ; ... passes.
    – sdaau
    Commented Oct 23, 2011 at 15:02
5

grep

Forgetting performance, this is POSIX and looks nicer than case solutions:

mystr="abcd"
if printf '%s' "$mystr" | grep -Eq '^ab'; then
  echo matches
fi

Explanation:

3

I tweaked @markrushakoff's answer to make it a callable function:

function yesNo {
  # Prompts user with $1, returns true if response starts with y or Y or is empty string
  read -e -p "
$1 [Y/n] " YN

  [[ "$YN" == y* || "$YN" == Y* || "$YN" == "" ]]
}

Use it like this:

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] y
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] Y
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] yes
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n]
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] n
false

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] ddddd
false

Here is a more complex version that provides for a specified default value:

function toLowerCase {
  echo "$1" | tr '[:upper:]' '[:lower:]'
}

function yesNo {
  # $1: user prompt
  # $2: default value (assumed to be Y if not specified)
  # Prompts user with $1, using default value of $2, returns true if response starts with y or Y or is empty string

  local DEFAULT=yes
  if [ "$2" ]; then local DEFAULT="$( toLowerCase "$2" )"; fi
  if [[ "$DEFAULT" == y* ]]; then
    local PROMPT="[Y/n]"
  else
    local PROMPT="[y/N]"
  fi
  read -e -p "
$1 $PROMPT " YN

  YN="$( toLowerCase "$YN" )"
  { [ "$YN" == "" ] && [[ "$PROMPT" = *Y* ]]; } || [[ "$YN" = y* ]]
}

Use it like this:

$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi

asfd [y/N]
false

$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi

asfd [y/N] y
true

$ if yesNo "asfd" y; then echo "true"; else echo "false"; fi

asfd [Y/n] n
false

Not the answer you're looking for? Browse other questions tagged or ask your own question.