How to compare strings in Bash

2018-12-31 19:30发布

How do I compare a variable to a string (and do something if they match)?

标签: string bash
10条回答
牵手、夕阳
2楼-- · 2018-12-31 20:21
a="abc"
b="def"

# Equality Comparison
if [ "$a" == "$b" ]; then
    echo "Strings match"
else
    echo "Strings don't match"
fi

# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
    echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
    echo "$b is lexicographically smaller than $a"
else
    echo "Strings are equal"
fi

Notes:

  1. Spaces between if and [ and ] are important
  2. > and < are redirection operators so escape it with \> and \< respectively for strings.
查看更多
闭嘴吧你
3楼-- · 2018-12-31 20:21

following script reads from a file named "testonthis" line by line then compares each line with a simple string, a string with special characters and a regular expression if it doesn't match then script will print the line o/w not.

space in bash is so much important. so following will work

[ "$LINE" != "table_name" ] 

but following won't:

["$LINE" != "table_name"] 

so please use as is:

cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 20:24

Bash4+ examples. Note: not using quotes will cause issues when words contain spaces etc.. Always quote in bash IMO.

Here are some examples BASH4+ :

Example 1, check for 'yes' in string (case insensitive):

    if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive) :

     if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

     if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

     if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

     if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match :

     if [ "$a" = "$b" ] ;then

enjoy.

查看更多
孤独寂梦人
5楼-- · 2018-12-31 20:25

I would probably use regexp matches if the input has only a few valid entries. E.g. only the "start" and "stop" are valid actions.

if [[ "${ACTION,,}" =~ ^(start|stop)$ ]]; then
  echo "valid action"
fi

Note that I lowercase the variable $ACTION by using the double comma's. Also note that this won't work on too aged bash versions out there.

查看更多
登录 后发表回答