Built-in Commands

Table of Contents

command reference

# If there is a shell function named `ls', running `command ls' within the function
# will execute the external `command ls' instead of calling the function `ls' recursively.
$ command ls

$ command -v 'curl'
#          └─ print the pathname or command that will be used by the shell

$ command -v 'curl' >/dev/null 2>&1; echo "$?"

$ command -v 'carl' >/dev/null 2>&1; echo "$?"

declare reference


export reference

export [-fn] [-p] [name[=value]]
# -f   The names refer to shell functions
#      otherwise the names refer to shell variables
# -n   no longer mark each name for export
# -p   Display output in a form that can be reused as input.

readonly reference

readonly var
readonly var=value
readonly p=/tmp/toi.txt
# error

readonly -f function_name
readonly -a array_name

readonly -p # print all readonly names
readonly VAR=foo   # POSIX
declare -r VAR=foo # bash

set reference

set -e # Exit immediately when a command fails
set -x # Print a trace of simple commands

set +x # Use + rather than -  to turn off.

set -- 'foo' 'bar' # set the positional parameters
echo "$1, $2"      # 'foo, bar'
set -euo pipefail
trap "echo 'error: Script failed: see failed command above'" ERR

trap reference

# signal
trap 'cmd' SIGINT

# SIG prefix is optional
trap 'cmd' INT

# special sigspec
trap 'cmd' EXIT   # on exit
trap 'cmd' DEBUG  # at every line
trap 'cmd' ERR    # on error. 'set -e' is more preferred

Apply set -x for a line howto

set -x
{ set +x; } 2>/dev/null

# or simply
( set -x; command )

Test whether a command exists howto

$ command -v 'curl'

$ command -v 'curl' >/dev/null 2>&1; echo "$?"

$ command -v 'carl' >/dev/null 2>&1; echo "$?"

Kill all background processes when the shell script exits howto

# signaling compatibility across shells
trap "exit" INT TERM ERR

# send TERM to the current process group when the shell script exits
trap "kill 0" EXIT

# jobs
./someProcessA &
./someProcessB &

# wait until jobs end