Limiting the scope of shell state changes

If you are going to change properties of the shell as a whole in part of your script, consider limiting the scope of that change only to the needed part of the script to avoid unexpected effects on the rest of it. Watch for these in particular:

  • The working directory
  • The positional parameters ($1, $2 ... )
  • Environment variables, especially PATH
  • Shell-local variables, especially IFS
  • Shell options with set (such as -x) or shopt (such as dotglob)
  • Shell resource limits set with ulimit

We already saw one effective means of limiting the scope of variables in Chapter 5, Variables and Patterns, by applying them as prefixes to a command:

IFS=: read -r name address

This limits the scope of the IFS change to ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.