set

Set or unset shell options and positional parameters.

Source: src/scripting/shell_options.f90:47-242

Synopsis

set [+-abefhkmnptuvxBCHP] [+-o option] [arg ...]
set --
set -

Description

The set builtin modifies shell behavior through options and manages positional parameters.

Options

Short Options

OptionLong FormDescription
-aallexportExport all variables automatically
-eerrexitExit on command failure
-fnoglobDisable pathname expansion
-hhashallHash commands on first use
-mmonitorEnable job control
-nnoexecRead commands but don't execute
-unounsetError on unset variables
-vverbosePrint input lines
-xxtracePrint commands before execution
-BbraceexpandEnable brace expansion
-CnoclobberDon't overwrite files with >
-HhistexpandEnable history expansion
-PphysicalUse physical directory structure

Enable/Disable

set -e      # Enable errexit
set +e      # Disable errexit

Long Options

set -o errexit      # Enable
set +o errexit      # Disable
set -o              # List all options

Positional Parameters

Set Parameters

set -- arg1 arg2 arg3
echo $1    # arg1
echo $2    # arg2
echo $@    # arg1 arg2 arg3

Clear Parameters

set --
echo $#    # 0

From Array

arr=(one two three)
set -- "${arr[@]}"

Examples

Error Handling

#!/usr/bin/env fortsh
set -euo pipefail

# Script exits on:
# - Any command failure (-e)
# - Use of unset variable (-u)
# - Pipeline failure (-o pipefail)

Debug Mode

set -x
echo "This will be traced"
# + echo 'This will be traced'
# This will be traced
set +x

Safe Scripts

set -euo pipefail
IFS=$'\n\t'

# Strict mode for scripts

Prevent File Overwrite

set -C
echo "data" > existing.txt    # Error if file exists
echo "data" >| existing.txt   # Force overwrite with >|

Common Option Combinations

Strict Mode

set -euo pipefail

Debug Mode

set -x

Interactive Safety

set -o noclobber
set -o notify

Checking Options

In Script

if [[ $- == *e* ]]; then
    echo "errexit is enabled"
fi

Current Options

echo $-           # Shows enabled short options
set -o            # Shows all options with on/off

Implementation Details

Source: shell_options.f90:47-242

Supported -o options:

  • allexport, errexit, hashall, monitor
  • noclobber, noexec, noglob, nounset
  • verbose, xtrace, pipefail, posix
  • braceexpand, histexpand, physical

Exit Status

StatusCondition
0Success
1Invalid option

Special Forms

set -          # Disable -x and -v
set --         # End of options marker
set            # Display all variables (no args)

Script Template

#!/usr/bin/env fortsh
set -euo pipefail

# Your script here...

cleanup() {
    # Cleanup code
}
trap cleanup EXIT

See Also