Bashscripting Grundlagen

Original Website

 

This is a quick reference to getting started with Bash scripting.

Example

Variables

String quotes

Shell execution

See Command substitution

Conditional execution

Functions

See: Functions

Conditionals

See: Conditionals

Strict mode

See: Unofficial bash strict mode

Brace expansion

Expression Description
{A,B} Same as A B
{A,B}.js Same as A.js B.js
{1..5} Same as 1 2 3 4 5

See: Brace expansion

Parameter expansions

Basics

See: Parameter expansion

Substitution

Code Description
${FOO%suffix} Remove suffix
${FOO#prefix} Remove prefix
${FOO%%suffix} Remove long suffix
${FOO##prefix} Remove long prefix
${FOO/from/to} Replace first match
${FOO//from/to} Replace all
${FOO/%from/to} Replace suffix
${FOO/#from/to} Replace prefix

Comments

Substrings

Expression Description
${FOO:0:3} Substring (position, length)
${FOO:(-3):3} Substring from the right

Length

Expression Description
${#FOO} Length of $FOO

Manipulation

Default values

Expression Description
${FOO:-val} $FOO, or val if unset (or null)
${FOO:=val} Set $FOO to val if unset (or null)
${FOO:+val} val if $FOO is set (and not null)
${FOO:?message} Show error message and exit if $FOO is unset (or null)

Omitting the : removes the (non)nullity checks, e.g. ${FOO-val} expands to val if unset otherwise $FOO.

Loops

Basic for loop

C-like for loop

Ranges

With step size

Reading lines

Forever

Functions

Defining functions

Returning values

Raising errors

Arguments

Expression Description
$# Number of arguments
$* All positional arguments (as a single word)
$@ All positional arguments (as separate strings)
$1 First argument
$_ Last argument of the previous command

Note: $@ and $* must be quoted in order to perform as described.
Otherwise, they do exactly the same thing (arguments as separate strings).

See Special parameters.

Conditionals

Conditions

Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition, see examples.

Condition Description
[[ -z STRING ]] Empty string
[[ -n STRING ]] Not empty string
[[ STRING == STRING ]] Equal
[[ STRING != STRING ]] Not Equal
[[ NUM -eq NUM ]] Equal
[[ NUM -ne NUM ]] Not equal
[[ NUM -lt NUM ]] Less than
[[ NUM -le NUM ]] Less than or equal
[[ NUM -gt NUM ]] Greater than
[[ NUM -ge NUM ]] Greater than or equal
[[ STRING =~ STRING ]] Regexp
(( NUM < NUM )) Numeric conditions

More conditions

Condition Description
[[ -o noclobber ]] If OPTIONNAME is enabled
[[ ! EXPR ]] Not
[[ X && Y ]] And
[[ X || Y ]] Or

File conditions

Condition Description
[[ -e FILE ]] Exists
[[ -r FILE ]] Readable
[[ -h FILE ]] Symlink
[[ -d FILE ]] Directory
[[ -w FILE ]] Writable
[[ -s FILE ]] Size is > 0 bytes
[[ -f FILE ]] File
[[ -x FILE ]] Executable
[[ FILE1 -nt FILE2 ]] 1 is more recent than 2
[[ FILE1 -ot FILE2 ]] 2 is more recent than 1
[[ FILE1 -ef FILE2 ]] Same files

Example

Arrays

Defining arrays

Working with arrays

Operations

Iteration

Dictionaries

Defining

Declares sound as a Dictionary object (aka associative array).

Working with dictionaries

Iteration

Iterate over values

Iterate over keys

Options

Options

Glob options

Set GLOBIGNORE as a colon-separated list of patterns to be removed from glob
matches.

History

Commands

Command Description
history Show history
shopt -s histverify Don’t execute expanded result immediately

Expansions

Expression Description
!$ Expand last parameter of most recent command
!* Expand all parameters of most recent command
!-n Expand nth most recent command
!n Expand nth command in history
!<command> Expand most recent invocation of command <command>

Operations

Code Description
!! Execute last command again
!!:s/<FROM>/<TO>/ Replace first occurrence of <FROM> to <TO> in most recent command
!!:gs/<FROM>/<TO>/ Replace all occurrences of <FROM> to <TO> in most recent command
!$:t Expand only basename from last parameter of most recent command
!$:h Expand only directory from last parameter of most recent command

!! and !$ can be replaced with any valid expansion.

Slices

Code Description
!!:n Expand only nth token from most recent command (command is 0; first argument is 1)
!^ Expand first argument from most recent command
!$ Expand last token from most recent command
!!:n-m Expand range of tokens from most recent command
!!:n-$ Expand nth token to last from most recent command

!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.

Miscellaneous

Numeric calculations

Subshells

Redirection

Inspecting commands

Trap errors

or

Case/switch

Source relative

printf

Directory of script

Getting options

Heredoc

Reading input

Special variables

Expression Description
$? Exit status of last task
$! PID of last background task
$$ PID of shell
$0 Filename of the shell script
$_ Last argrument of the previous command

See Special parameters.

Go to previous directory

Check for command’s result

Grep check

Also see

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Back To Top