Signup/Sign In

Set and Unset shell option with shopt command in Linux

The shopt command is a shell builtin in Bash (Bourne Again Shell) and other Bash-like shells. It allows users to set and unset shell options that affect the behavior of the shell and the commands it executes. The shopt command is often used in shell scripts to modify the behavior of the script or to enable certain features that may not be enabled by default.

Syntax of shopt command:

shopt: shopt [-pqsu] [-o] [optname ...]

Change the setting of each shell option OPTNAME. Without any option arguments, list each supplied OPTNAME, or all shell options if no OPTNAMEs are given, with an indication of whether or not each is set.

Options/Flags in shopt command:

-o restrict OPTNAMEs to those defined for use with `set -o`
-p print each shell option with an indication of its status
-q suppress output
-s enable (set) each OPTNAME
-u disable (unset) each OPTNAME

Exit Status:

  1. Returns success if OPTNAME is enabled.
  2. Fails if an invalid option is given or OPTNAME is disabled.

Linux terminal executing shopt command

Example usage of shopt command

Here are some examples of using the shopt command:

  1. To enable the cdable_vars option, which allows the use of variables as arguments to the cd command, use the following command:
$ shopt -s cdable_vars
  1. To disable the cdable_vars option, use the following command:
$ shopt -u cdable_vars
  1. To display a list of all the options that are currently set, use the following command:
$ shopt

This will display a list of all the options and their current values.

Conclusion

The shopt command is a useful tool for modifying the behavior of the shell and the commands it runs. It can be used in shell scripts to enable or disable certain features, or to customise the behavior of the script.



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.