Bash shell provides different builtin commands to manage the bash environment. The set
command is used to manage some flags and characteristics of the bash environment. The set command can be used to change different parameters of the bash shell environment and customized for different cases and users.
set Command Help
The set command provides a lot of options but we will only examine the most popular of them. All options about the set command can be displayed with the --help
option like below.
$ set --help
Prevents File Overwriting
By default, bash provides the echo command in order to print or redirect content to the stdout which can be also a file. If the file has some content this content is overwritten if another content is redirected into it by using commands like an echo. This is the default bash configuration which does not prevents overwriting. By using the set -C
command this overwriting setting can be disabled and existing file content can not be overwritten via bash.
$ set -C
From the output, we can see that “cannot overwrite existing file” error is returned by bash shell.
Disable Glob Operator
Bash provides the glob operator
which is also called as Globbing
. The *
sign is used as globbing operator. The glob operator is used for file name generation by default. But the glob operator or file generation can be disabled by using the set -f
command.
$ set -f
We can see that the “ls: cannot access ‘*’: No such file or directory” error is returned when we try to use glob operator.
Debug Bash Script
Debugging is used to troubleshoot applications and scripts. Bash provides the debugging features and the set -
x command is used to enable bash script debugging. The debugging will print all executed commands line by line by putting +
at the start of the debugging line. The outputs does not have +
at the start of the line.
$ set -x
Prevent Unused Variables
Bash variables are used to store different types of information. It is expected that a variable should be initialized and used properly. The set -u
command can be used to prevent and print errors for the unused variables in bash scripts.
$ set -u
Export Variables
Every bash shell has its own environment where defined variables can be only used for their own environment. But exporting makes the defined variables to be used in other bash shells or environments. The set -a
command can be used to make defined variables exported automatically to the other bash shells.
$ set -a
In the following example, we will set the all bash shell variable as exportable and then call the script example.sh
which will use the shell variables defined previously which is name
in this example.