Bash Code Examples

See also
Bash Resources
Bash Code Examples
Data Tools
Bash Dates

Brackets

if [ CONDITION ]    Test construct
if [[ CONDITION ]]  Extended test construct
Array[1]=element1   Array initialization
[a-z]               Range of characters within a Regular Expression
$[ expression ]     A non-standard & obsolete version of $(( expression )) [1]

[1] http://wiki.bash-hackers.org/scripting/obsolete

Curly Braces

${variable}                             Parameter substitution
${!variable}                            Indirect variable reference
{ command1; command2; . . . commandN; } Block of code
{string1,string2,string3,...}           Brace expansion
{a..z}                                  Extended brace expansion
{}                                      Text replacement, after find and xargs

===== Parentheses =====
( command1; command2 )             Command group executed within a subshell
Array=(element1 element2 element3) Array initialization
result=$(COMMAND)                  Command substitution, new style
>(COMMAND)                         Process substitution
<(COMMAND)                         Process substitution

Double Parentheses

(( var = 78 ))            Integer arithmetic
var=$(( 20 + 5 ))         Integer arithmetic, with variable assignment
(( var++ ))               C-style variable increment
(( var-- ))               C-style variable decrement
(( var0 = var1<98?9:21 )) C-style ternary operation

Conditionals

! EXPRESSION 	The EXPRESSION is false.
-n STRING 	The length of STRING is greater than zero.
-z STRING 	The lengh of STRING is zero (ie it is empty).
STRING1 = STRING2 	STRING1 is equal to STRING2
STRING1 != STRING2 	STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2 	INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2 	INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2 	INTEGER1 is numerically less than INTEGER2
-d FILE 	FILE exists and is a directory.
-e FILE 	FILE exists.
-r FILE 	FILE exists and the read permission is granted.
-s FILE 	FILE exists and it's size is greater than zero (ie. it is not empty).
-w FILE 	FILE exists and the write permission is granted.
-x FILE 	FILE exists and the execute permission is granted.

Snippets

Generate passwords
openssl rand -base64 32

Convert eg "LIST-tc4" to "tc4"
mv "$i" "${i#LIST-}";
(suffix would be % insteadof #)

Print Every Nth Line
awk '!(NR%3)'

If file doesn't exist
[ ! -f $file ]

If file or folder doesn't exist
[ ! -e $file ]

Within a script, return the folder that the script is in, regardless of where it's called from
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

Date examples
+"%Y-%m-%d" (0 padded) 2019-08-25
+"%a %b %d" - Sun Jan 01



Backlinks: knowledgebase:Bash Code Examples knowledgebase:COMMAND LINE knowledgebase:Terminal Apps