Sh - String Variable

Bash Liste Des Attaques Ovh

About

String Variable, see also character

string in bash.

Initialization

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

Initialization from File

#!/bin/sh
echo 'hello' > hello.txt
test=`cat hello.txt `
echo $test
hello

  • Bash
#!/bin/bash
value=$(<file.txt)
echo "$value"

Quote

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.

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.

EOL Bash

The below code will produce:

var=$'Hello\nWorld'
echo $var
Hello
World

EOL Posix compliant
BAR=$(printf "hello\nworld\n")

Escape

The escape character is a backslash \

Function

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


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

Substring

Example:

UNKNOWN=unknown
echo ${UNKNOWN:2:3} 
kno

  • The last 3 digits
echo ${UNKNOWN: -3} # the space is important, get the 
  • or with cut
echo "nicolas" | cut -c1-4
nico

  • Last three character
echo -n "nicolas" | tail -c 3
  • From to (from 2 to -2) - rev reverse the string
echo -n "nicolas" | cut -c2- | rev | cut -c2- | rev
icola

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:

Length

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

MY_VARIABLE=123
echo ${#MY_VARIABLE}
3

Uppercase / Lowercase / InitCap / CamelCase

  • 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

Replace

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}
  • The Escape character is the \ backslash
word="hello/nico"
# Replacing the / character with a space
echo ${word//\// }
hello nico

Others

See also:

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)

to Array

IFS=', ' read -r -a array <<< "$string"

example

IFS=',' read -r -a myArray <<< "hello,nico"
echo ${#myArray[*]} # length of 2
echo ${myArray[*]}
hello nico

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!"

Comparison Operator

Comparison operator in bash conditional expression for strings.

  • = : is equal to. With the whitespace framing the = equals 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 a "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
  • You can also use the named comparison operators (demo is for integer but they works also for string)
Double Bracket operator Single Bracket Operator Example
-lt -lt [[ 8 -lt 9 ]] && echo "8 is less than 9"
-ge -ge [[ 3 -ge 3 ]] && echo "3 is greater than or equal to 3"
-gt -gt [[ 5 -gt 10 ]] || echo "5 is greater than than 10"
-le -le [[ 3 -le 8 ]] && echo "3 is less than or equal to 8"
-eq -eq [[ 5 -eq 05 ]] && echo "5 equals 05"
-ne -ne [[ 6 -ne 20 ]] && echo "6 is not equal to 20"

Contains

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

Example:

if [[ ! "${DIRECTORY_TO_CLEAN}" =~ ^(/opt/infa/|/home/).* ]] ; then
    echo_err "Directory To Clean parameter must be a directory inside /opt/infa or /home/"
    close_script 1
fi

Documentation / Reference





Discover More
Bash Liste Des Attaques Ovh
Bash - (Environment) Variable

A variable is a parameters referenced by a name. parameter A variable has: a value and zero or more attributes (such as integer, ...). Attributes are assigned using the declare builtin command....
Bash Liste Des Attaques Ovh
Bash - Character

Character section of bash. See also:
Bash Liste Des Attaques Ovh
Bash - Conditional Expression

A predicate or boolean expression is known in Bash as a Conditional Expression. It is a command that returns an exit status of 0 or 1. The conditional expression is part of the compound expression. ...
Bash Liste Des Attaques Ovh
Bash - How to pass arguments that have space in their values ?

This article shows you how to pass arguments that have space characters in their values. Passing several arguments to a function that are stored as a string may not work properly when you have space...
Bash Liste Des Attaques Ovh
Bash - IFS (Field Separator)

The field separator is a set of character that defines one or more field separator that separates (delimit) field (word) in a string. DELIM It's defined in the IFS variable parameters statement...
Bash Liste Des Attaques Ovh
Bash - Parameter Expansion ${

Parameter expansion are patterns applied to the parameters that have different results. Same as ?? See also: The value of parameter is substituted where: the braces are optional. They served...
Bash Liste Des Attaques Ovh
Bash - Standard input (stdin)

operations that applied only to the bash|bash shell See The input redirection operator takes the content of a file and send it as standard input Example with read that take a stand Create...
Bash Liste Des Attaques Ovh
How to use the Array Variable in Bash?

Bash provides a one-dimensional array variables. See also: When calling a function, quote the variable otherwise bash will not see the string as atomic. The separator is variable $IFS. There is: ...
Bash Liste Des Attaques Ovh
Sh - Backslash Escape Characters (Whitespace, Tabs, Ends, End of Line, Newline) - Non-printing characters

in bash 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. Backslash escape sequences,...
Card Puncher Data Processing
Shell Data Processing - Sed (Stream editor)

sed stands for stream editor. It is a filter program used for filtering and transforming text It: takes as input a standard stream input modifies it based on an expression, and returns it as...



Share this page:
Follow us:
Task Runner