String Operators

# Length ${#string}
= Equal [[ $a = $b ]]
!= Not equal [[ $a != $b ]]
> Greater than [[ $a > $b ]]
< Less than [[ $a < $b ]]
-z is Zero [[ -z $a ]]
-n is non Zero [[ -n $a ]]
str Assigned [[ $a ]]

*note: above is using pseudo ternary one liner with && and || replacing normal ? and :

 

 

Substrings

 

The following tests whether a string contains substring:

 

Substring extraction

 

Extract from a position and from a position with length

 

${string:position}

${string:position;length}

 

 

Substring removal

 

Remove shortest starting match.

If string starts with substring, delete the shortest part that matches the substring:

${string#*substring}

 

Remove longest starting match.

If string starts with substring, delete the longest match from string and return the rest:

${string##substring}

 

Remove shortest ending match.

If string ends with substring, delete the shortest match from the end of string and return the rest:

${string%substring*}

 

Remove longest ending match.

If string ends with substring, delete the longest match from the end of string and return the rest:

${string%%substring*}

 

 

 

Substring replacement

 

Replace first occurrence of substring with replacement.

 

If replacement is null, substring is deleted from string.

${string/substring/replacement}

 

If substring matches the front end of  string, substitute replacement for  substring.

${string/#substring/replacement}

 

If substring matches the back end of  string, substitute replacement for  substring.

${string/%substring/replacement}

 

Replace all occurrences of substring.

${string//substring/replacement}

 

If sub is null, substring is deleted from variable.

 

 

 

Substring extraction

 

Extract substring from string at position;

${string:position}

 

Extract length characters of substring from string at position;

${string:position:length}