0

This is probably simple to fix but I can't seem to find a solution that works on here.

I can't figure out why this if statement is evaluating to true:

#/bin/bash

err="User dimensions query limit exceeded"

if [ "${err}" != "User"* ]; then
    echo "In the if statement"
    exit 1
fi

I've tried various combinations of parentheses and moving the * about, changing != to -ne etc. but to no avail.

Thanks.

cjt00
  • 3
  • 1
  • 1
    POSIX `sh` does not support string match like that, you need to use `case` statment if targeting scripts for POSIX compatibility or use bash's extended test operator `[[` – Inian Aug 08 '23 at 11:31
  • [Shellcheck](https://www.shellcheck.net/) identifies several problems with the code. The report includes links to more information about the problems and how to fix them. It's a good idea to run [Shellcheck](https://www.shellcheck.net/) on all new and modified shell code. – pjh Aug 08 '23 at 11:32
  • The bash-internal command `[` does not support wildcard matching. It behaves in this respect like the external command `[` (see _man test_). – user1934428 Aug 08 '23 at 11:35
  • Does this answer your question? [Difference between single and double square brackets in Bash](https://stackoverflow.com/questions/13542832/difference-between-single-and-double-square-brackets-in-bash) – pjh Aug 08 '23 at 11:36
  • Also: https://www.gnu.org/software/bash/manual/bash.html#index-_005b_005b – glenn jackman Aug 08 '23 at 11:47

1 Answers1

2

I believe it's because you're using [ ... ] instead of [[ ... ]]. My guess is that filename expansion is being performed on "User"*, when you don't want it to be.

Just using the bash-specific [[ and ]] should fix it:

#/bin/bash

err="User dimensions query limit exceeded"

if [[ "${err}" != "User"* ]]; then
    echo "In the if statement"
    exit 1
fi

At that point I suspect the condition line could be simplified due to how bash handles [[ ... ]] to:

if [[ $err != User* ]]; then

... but I don't know enough about the details to be 100% confident. (It works in my brief tests...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194