Monday 25 December 2017

In Bash, how can I check if a string begins with some value?

itemprop="text">

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
can I do it correctly?


itemprop="text">
class="normal">Answer



This
snippet on the rel="noreferrer">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).



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...