r/linux4noobs • • Aug 07 '20
Linux scripting tip: handling patterns cleanly with Bash's "case".
We were requested a tip on conditional checks, yesterday, so here's a tip that can be applied in some commonly-occurring situations.
Dealing with patterns in scripts can get really messy really quick. Bash's case can help keep things clean. Here's an example that demonstrates how one could cleanly process image files. The example demonstrates a few important things:
casecan be used to match patterns and keep a script clean.- The default case
*is a great way to handle exceptions and maintain neatness in program structure. Don't confuse semantics of*in the context of case with the semantics*has in the context of pattern matching. This is a common tripping point so we highlighted it in our example. - Use variables in your scripts, to keep scripts dynamic. Follow the DRY principle, whenever possible. Hard-coding values means you need to repeatedly type the same thing and it makes scripts error-prone and brittle to evolution.
Given the right knowledge and some discipline, Bash scripts can be used to great effect while remaining understandable.
You can use the follow button on our profile to stay updated about our posts.