Determining if the first string starts with second string

10,963

Solution 1

set world

Then:

if [ "${1%%w*}" ]
then
  echo false
else
  echo true
fi
  1. Aggressively remove substring starting with w from source string
  2. If anything left, then source string does not start with second string

Or:

if [ "$1" = "${1#w}" ]
then
  echo false
else
  echo true
fi
  1. Remove w from source string
  2. Compare with source string
  3. If equal, then source string does not start with second string

Solution 2

If your shell is bash: within double brackets, the right-hand side of the == operator is a pattern unless fully quoted:

if [[ world == w* ]]; then
    echo true
else
    echo false
fi

Or more tersely: [[ world == w* ]] && echo true || echo false [*]

If you are not targetting bash specifically: use the case statement for pattern matching

case "world" in
    w*) echo true ;;
    *)  echo false ;;
esac

[*] but you need to be careful with the A && B || C form because C will be executed if either A fails or B fails. The if A; then B; else C; fi form will only execute C if A fails.

Share:
10,963

Related videos on Youtube

user1730706
Author by

user1730706

Hello world

Updated on September 18, 2022

Comments

  • user1730706
    user1730706 almost 2 years

    JavaScript has a function for this:

    'world'.startsWith('w')
    true
    

    How can I test this with shell? I have this code:

    if [ world = w ]
    then
      echo true
    else
      echo false
    fi
    

    but it fails because it is testing for equality. I would prefer using a builtin, but any utilities from this page would be acceptable:

    http://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html