set
Set and unset shell options, display variables, and set positional parameters
Syntax
set [options] [arguments]
Basic Usage
Display all shell variables
set
Shows all shell variables and their values.
Display shell options
set -o
Shows all shell options and their current state.
Set positional parameters
set arg1 arg2 arg3
Sets $1, $2, $3 to the specified arguments.
Common Options
-a, --allexport: Automatically export all variables-b, --notify: Report job termination immediately-e, --errexit: Exit on any error-f, --noglob: Disable filename expansion-h, --hashall: Remember command locations-k, --keyword: All assignment arguments are placed in environment-m, --monitor: Enable job control-n, --noexec: Read commands but don't execute-o option: Set option by name-p, --privileged: Turn on privileged mode-t, --onecmd: Exit after reading and executing one command-u, --nounset: Exit on undefined variable references-v, --verbose: Print shell input lines-x, --xtrace: Print commands and their arguments
Practical Examples
View current shell variables
set | head -20
Enable error exit on any command failure
set -e
Enable verbose mode and exit on error
set -ve
Set positional parameters
set "first arg" "second arg" "third arg"
Display specific option status
set -o | grep errexit
Enable debugging mode
set -x
Disable filename expansion
set -f
Reset all options to default
set +o
Shell Options
Common Shell Options
- errexit: Exit on any command failure
- nounset: Exit on undefined variable references
- xtrace: Print commands before execution
- verbose: Print shell input lines
- noglob: Disable filename expansion
- monitor: Enable job control
- hashall: Remember command locations
Best Practices
When to Use
- Debugging shell scripts
- Setting strict error handling
- Controlling shell behavior
- Managing positional parameters
- Script debugging and development
Important Notes
- Options set with 'set' affect the current shell session
- Use 'set +o option' to disable an option
- Some options can make scripts more robust (e.g., -e, -u)
- Be careful with -f option as it disables globbing
- Options can be combined (e.g., 'set -ex')
- Consider using 'set -euo pipefail' for robust scripts