2 minutes
Bash
Length
Depending on var type you can have the length of the variable :
$ TEST=toto
$ echo ${TEST}
toto
$ echo ${#TEST}
4
$ ARR=(toto tata titi)
$ echo ${#ARR}
3
Default
If you want to put default value to your variable you can as well :
$ echo ${TEST:-toto}
toto
$ echo ${TEST}
$ TEST=titi
$ echo ${TEST:-toto}
titi
You can also assign default :
$ echo ${TEST:=toto}
toto
$ echo ${TEST}
toto
You can also test if assigned
$ echo ${TEST:?"No value there"}
-bash: TEST: No value there
$ TEST=toto
$ echo ${TEST:?"No value there"}
toto
Transformations
Removal
You can remove pattern in varaible using #
(from left) or %
(from right)
$ TEST="tototatatititatatoto"
$ echo ${TEST#*tata}
tititatatoto
$ echo ${TEST%tata*}
tototatatiti
This will remove the shortest pattern
You can also remove the longest pattern with this :
$ TEST="tototatatititatatoto"
$ echo ${TEST##*tata}
toto
$ echo ${TEST%%titi*}
tototata
You can do the same on array and it will apply to each member :
$ TEST=(toto tata titi tata toto)
$ echo ${TEST[@]#toto}
tata titi tata
$ echo ${TEST[@]#*a}
toto ta titi ta toto
$ echo ${TEST[@]##*a}
toto titi toto
Change of case
You can do some upper or lower case change directly on the variable:
$ TEST="TOTO"
$ echo "${TEST,}"
$ tOTO
$ echo "${TEST,,}"
$ toto
And the opposite :
$ TEST="toto"
$ echo "${TEST^}"
$ Toto
$ echo "${TEST^^}"
$ TOTO
Substitution
Same as using sed pretty much :
$ TEST="tototatatititatatoto"
$ echo ${TEST/o/a}
tatotatatititatatoto
$ echo ${TEST//o/a}
tatatatatititatatata
Read other posts
comments powered by Disqus