Bash idioms

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.

More little tricks


Print Every Nth Line

awk '!(NR%3)'

If file exists

[ ! -f $file ]

Generate passwords

openssl rand -base64 32
('32' can be changed to whatever length you want. This is probably as good as any method you'll see anywhere)




Backlinks: LibraryZim:Bash:BigThing