0

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

5

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.