I would like to check if a string begins with "node" e.g. "node001". Something like
if [ $HOST == user* ]
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 to do it correctly?
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.
@OP, for both your questions you can use case/esac
second question
OR Bash 4.0
I prefer the other methods already posted, but some people like to use:
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 you're using a recent bash (v3+), I suggest bash regex comparison operator
=~
, i.e.To match
this or that
in a regex use|
, i.e.Note - this is 'proper' regular expression syntax.
user*
meansuse
and zero-or-more occurrences ofr
, souse
anduserrrr
will match.user.*
meansuser
and zero-or-more occurrences of any character, souser1
,userX
will match.^user.*
means match the patternuser.*
at the begin of $HOST.If you're not familiar with regular expression syntax, try referring to this resource.
Note - it's better if you ask each new question as a new question, it makes stackoverflow tidier and more useful. You can always include a link back to a previous question for reference.
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.
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:Or even shorter
Or even shorter (just to present
!
as a language element -- but this is bad style now)If you like being explicit, build your own language element:
Isn't this actually quite nice?
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:
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 must use strings. But nesting function calls with strings is not possible, pipes are not possible...)
This snippet on the Advanced Bash Scripting Guide says:
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:
Which will echo
Bash's
if
syntax is hard to get used to (IMO).