Built-in Commands
Table of Contents
command
declare
export
readonly
set
trap
- Apply
set -x
for a line - Test whether a command exists
- Kill all background processes when the shell script exits
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
/usr/bin/curl
$ command -v 'curl' >/dev/null 2>&1; echo "$?"
0
$ command -v 'carl' >/dev/null 2>&1; echo "$?"
1
declare
reference
-x
- export
export
reference
- Mark each name to be passed to child processes in the environment.
- It doesn't matter whether you set a variable before
export
or vice versa.
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
p=/tmp/newvale
readonly -f function_name
readonly -a array_name
readonly -p # print all readonly names
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'
-e
for errors-u
for preventing unset-o pipefail
for errors within pipes
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
Test whether a command exists howto
$ command -v 'curl'
/usr/bin/curl
$ command -v 'curl' >/dev/null 2>&1; echo "$?"
0
$ command -v 'carl' >/dev/null 2>&1; echo "$?"
1
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
wait
- signals are propagated to subprocesses by default
- However, shells like
bash
set the signal mask ofSIG_IGN
toSIGINT
andSIGQUIT
- So, by using
trap
, sendTERM
to subprocess manually when the parent script exits - If the subprocess handles
SIGINT
manually, it would receive both signals ofSIGINT
andSIGTERM