-2

I am wanting to use a switch/ case statement in bash to check if a file name which is a string contains something but also does not.

Here is my case:

case "$fileName" in
    *Failed|!cp*)
       echo "match"
     ;;
esac

But this does not work currently, how can I see if the string matches "Failed" but also does not contain "cp"?

It would be great if this could be done in a switch/ case as well

Erdss4
  • 1,025
  • 3
  • 11
  • 31
  • `|` in a case is for OR, not AND. – Barmar Aug 31 '18 at 10:50
  • How would I do an AND? – Erdss4 Aug 31 '18 at 10:50
  • Possible duplicate of [Switch case with fallthrough?](https://stackoverflow.com/q/5562253/608639) Also see [How to use Shellcheck](https://github.com/koalaman/shellcheck), [How to debug a bash script?](https://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](https://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](https://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Aug 31 '18 at 12:15

2 Answers2

2

! has to be followed by a parenthesized list of patterns, not the pattern itself.

| in a case is for OR, not AND. To get AND, you should nest cases.

case "$fileName" in
    *Failed)
        case "$fileName" in
            cp*) ;;
            *) echo "match" ;;
        esac
     ;;
esac

Or you could just use if instead of case:

if [[ $filename = *Failed && $filename != cp* ]]
then echo match
fi
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Alternatively you can use if and pipes for instance:

if echo 'Failed' | grep -v cp | grep -q Failed ; then
    echo Failed without cp
else
    echo It's either Winned or cp.
fi
bipll
  • 11,747
  • 1
  • 18
  • 32