Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

bash - Case statement with extglob

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...