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

ExpressionDescription
{A,B}Same as A B
{A,B}.jsSame as A.js B.js
{1..5}Same as 1 2 3 4 5

See: Brace expansion

Parameter expansions

Basics

See: Parameter expansion

Substitution

CodeDescription
${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

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

Length

ExpressionDescription
${#FOO}Length of $FOO

Manipulation

Default values

ExpressionDescription
${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

ExpressionDescription
$#Number of arguments
$*All positional arguments (as a single word)
$@All positional arguments (as separate strings)
$1First 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.

ConditionDescription
[[ -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

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

File conditions

ConditionDescription
[[ -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

CommandDescription
historyShow history
shopt -s histverifyDon’t execute expanded result immediately

Expansions

ExpressionDescription
!$Expand last parameter of most recent command
!*Expand all parameters of most recent command
!-nExpand nth most recent command
!nExpand nth command in history
!<command>Expand most recent invocation of command <command>

Operations

CodeDescription
!!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
!$:tExpand only basename from last parameter of most recent command
!$:hExpand only directory from last parameter of most recent command

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

Slices

CodeDescription
!!:nExpand 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-mExpand 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

ExpressionDescription
$?Exit status of last task
$!PID of last background task
$$PID of shell
$0Filename 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

Kategorie(n): Anleitungen, Bash, IT Syntax

Schreibe einen Kommentar

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

 

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.