Sh - String Variable

1 - About

String Variable

string in bash.

3 - Initialization

3.1 - Function Arg

When calling a function, quote the variable otherwise bash will not see the string as atomic but as an array

output_args()
{
  for arg
  do
    echo "$arg"
  done
}
var="hello Nico"
 
echo "Without Quotes"
echo "**************"
output_args $var
echo 
echo "With Quotes"
echo "**************"
output_args "$var"
Without Quotes
**************
hello
Nico

With Quotes
**************
hello Nico

3.2 - Initialization from File

#!/bin/sh
echo 'hello' > hello.txt
test=`cat hello.txt `
echo $test
hello
  • Bash
#!/bin/bash
value=$(<file.txt)
echo "$value"

3.3 - Quote

3.3.1 - Double Quote - $"string"

The default for a string variable

var="My string"

A double-quoted string preceded by a dollar sign $“string” will cause the string to be translated according to the current locale.

If the current locale is C or POSIX, the dollar sign is ignored.

If the string is translated and replaced, the replacement is double-quoted.

3.3.2 - Single Quote - $'string'

From the bash man page, words of the form $'string' are treated specially.

The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

The expanded result is single-quoted, as if the dollar sign had not been present.

3.3.2.1 - EOL Bash

The below code will produce:

var=$'Hello\nWorld'
echo $var
Hello
World
3.3.2.2 - EOL Posix compliant
BAR=$(printf "hello\nworld\n")

3.4 - Escape

The escape character is a backslash \

4 - Function

4.1 - Concatenation

Write the variable one after another:

  • Concatenation without space:
var1=Hello
var2=Nico
echo $var1$var2
HelloNico
var1=Hello
var2=Nico
echo $var1 $var2
Hello Nico
  • concatenation with space
var3="${var1} ${var2}"
echo $var3
Hello Nico
  • Concat with the += assignment operator. value is expanded and appended to the variable’s value.
MY_VARIABLE=A
MY_VARIABLE+=B
echo $MY_VARIABLE
AB
variable="First"$'\n'
variable=$variable"Second"$'\n'
echo "$variable"
First
Second

4.2 - Split

  • Cut: Split on a line level
echo -e 'One,Two,Three,Four\nOne,Two,Three,Four' | cut -d ',' -f 1-2,4 --output-delimiter=' '
One Two Four
One Two Four

4.3 - Substring

Example:

UNKNOWN=unknown
echo ${UNKNOWN:2:3} 
kno
  • or with cut
echo "nicolas" | cut -c1-4
nico

4.4 - Remove a part

With Parameter Expansion Removal operation, you can remove a part of the string.

MY_VARIABLE=123
echo ${MY_VARIABLE#1}
23

See also:

4.5 - Length

With length parameter expansion, you can get the length of a string variable.

MY_VARIABLE=123
echo ${#MY_VARIABLE}
3

4.6 - Uppercase / Lowercase / InitCap

  • Before bash 4:
# From upper to lower
echo "HELLO WORLD" | tr '[:upper:]' '[:lower:]'
# With a variable
X=$(echo "${X}" | tr '[:upper:]' '[:lower:]')
  • With Bash 4:
hello="HELLO WORLD"
echo  ${hello,,} # Lowercase
echo  ${hello,} # Lowercase First letter
echo  ${hello^^} # Uppercase
echo  ${hello^} # Uppercase First letter

4.7 - Replace

4.7.1 - Bash parameters expansion

Replacement with parameter expansion ?

  • Replace first match of substring with replacement.
${string/substring/replacement}
 
# Replacing all / in a path
foo=`pwd`
echo ${foo////_}
  • Replace all matches of substring with replacement.
${string//substring/replacement}
  • If substring matches front end of string, substitute replacement for substring.
${string/#substring/replacement}
  • If substring matches back end of string, substitute $replacement for substring.
${string/%substring/replacement}

4.7.2 - Others

4.8 - Extract

regexp=$'[^ ]*\s(.*)' # Mandatory to put the regexp in a variable
if [[ "Hello Nico" =~ $regexp ]]; then echo "Match : First group is (${BASH_REMATCH[1]})"; else echo "No match"; fi;
Match : First group is (Nico)

5 - Comparison

Name Double Bracket operator Single Bracket Operator Example
Greater than > \> (*) [[ a > b ]] || echo "a does not come after b"
Lower than < \< (*) [[ az < za ]] && echo "az comes before za"
Equality = (or ==) = [[ a = a ]] && echo "a equals a"
Not Equal != != [[ a != b ]] && echo "a is not equal to b"
Pattern matching = (or ==) (not available) [[ $name = a* ]] || echo "name does not start with an 'a': $name"
RegularExpression matching =~ (not available) [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!"

5.1 - Comparison Operator

  • = : is equal to. With the whitespace framing the = equal char.
if [ "$a" = "$b" ] 
#  is not the same than (Why???)
if [ "$a"="$b" ]
  • == is equal to.
if [ "$a" == "$b" ] # Synonym of ''=''
 
[[ $a == z* ]]   # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
 
[ $a == z* ]     # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
  • < is less than, in ASCII alphabetical order
if [[ "$a" < "$b" ]]
if [ "$a" \< "$b" ] # The "<" char needs to be escaped in a [ construct
  • != is not equal to. Pattern matching within a [[ ... ]] construct.
if [ "$a" != "$b" ]
  • -z string has zero length
  • -n string is not null

Example: Quote strings within test brackets as the variable may be not initialized

if [ -n "$string1" ]  
then
  echo "String \"string1\" is not null."
else  
  echo "String \"string1\" is null."
fi

5.2 - Contains

See equality operator above with the [[ ... ]] construct.

6 - Documentation / Reference

lang/bash/string.txt · Last modified: 2018/12/14 11:16 by gerardnico