Shell – Determining if the first string starts with second string

shelltest

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

Best Answer

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.

Related Question