Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case statement with extglob

Tags:

bash

With extglob on, I want to match a variable against

*( )x*

(In regex: /^ *x.*/)

This:

main(){
  shopt -s extglob
  local line=' x bar'
  case "$line" in
    *( )x*) ;;
    *) ;;
  esac
}
main "$@"

is giving me a syntax error. Either removing the extglob parentheses or moving shopt -s extglob outside of main, to the outer scope, fixes the problem. Why? Why does the shopt -s extglob command need to be outside?

like image 751
PSkocik Avatar asked Jan 20 '16 22:01

PSkocik


2 Answers

bash has to parse the function in order to create it, and since the extended glob syntax you're using would normally be invalid, it can't parse the function unless extglob is on when the function is created.

Net result: extglob has to be on both when the function is declared and when it runs. The shopt -s extglob line in the function takes care of the second requirement, but not the first.

BTW, there are some other places where this can be a problem. For example, if you have a while or for loop, bash needs to parse the entire loop before beginning to run it. So if something in the loop uses extglob, you have to enable it before the beginning of the loop.

like image 117
Gordon Davisson Avatar answered Nov 18 '22 00:11

Gordon Davisson


You're missing the in keyword.

case "$var" in
    *( )x*) echo yes;;
esac 
like image 22
John Kugelman Avatar answered Nov 18 '22 01:11

John Kugelman