Bash Shell Scripting...

The Bourne Again SHell (bash)... written by Brian Fox... is the sucessor of the Bourne SHell (sh) written by Stephen Bourne. It comes with most linux distros... is easy to use and has quite a few tricks up it's sleeve.

CREATED 2012-11-18 18:10:44.0


UPDATED 2012-11-18 18:10:54.0

String Subtitution...

Substitution operators. In bash or linux a null and blank or empty are all the same.

  • ${var:-word}
    • word is returned if var is null or undefined, otherwise the value of var is returned

    • Example: ${domain:-""} - if $domain is not instantiated or is null the value is returned but the variable $domain remains as it was.

  • ${var:=word}
    • word is set as the value of var if var does not exist or is null then the value is returned.

    • ${domain:=""} returns the value of $domain if the variable is instantiated and is not null or blank. Otherwise the variable is instantiated and it's value is set to "" which is returned.

  • ${var:?message}
    • The message is printed as "var: message" if var is null or undefined otherwise the value of var is returned.

    • domain: Domain is undefined

      Example: ${$domain:?"Domain undefined"} prints the message

      if the variable $domain is undefined or null. Otherwise it returns the value of $domain.

  • ${var:+word}
    • if $domain is defined and has a value assigned to it otherwise null is returned.
    • Returns word if var is defined and not null. Otherwise it returns null

    • Already Defined

      ${$domain:+"Already Defined"} returns

CREATED 2017-04-18 14:11:22.0


UPDATED 2017-04-18 15:32:12.0

Variable Length

To determine the length of a string to use the pound (#) sign.

$ myVar="This is a test"
$ printf "Length of myVar: %d " "$myVar"

CREATED 2017-09-03 21:13:16.0


UPDATED 2020-03-31 09:48:32.0


Strings in bash are indext 0..length

$ myString=This is a test
$ echo ${myString:0:4} This ode>

CREATED 2017-09-03 22:02:52.0


UPDATED 2020-03-31 09:48:34.0

Find a string in a set...

Find a string in a set of strings using regex. This only works in BASH >=3.0...

[[ "$word" =~ "^(hello|hi)$" ]] && echo "Yes\n" || echo "No"

CREATED 2018-12-10 12:50:15.0


UPDATED 2020-03-31 09:48:35.0

Create a new blank file...

To create an empty file...

$ $(> /path/to/file)

CREATED 2017-09-03 22:15:29.0


UPDATED 2020-03-31 09:48:35.0

Read a variable from a pipe...

connip=$(echo ${logLine##*[} | { read pLine; echo ${pLine%%]*}; })

The catch in this snippit is the read pLine; statement. That gets the variable from the previous command (the one before the pipe).

CREATED 2021-01-05 13:49:44.0


UPDATED 2021-01-05 13:50:01.0


Bash Hackers Wiki

DBID: db.wam

Page Server: Ruger

©2012 Leistware Data Systems

      Hello anonymous