Week 5 Part 2 Flashcards
how to create a shell variable?
myvar=”value string”
variables cannot start with a number and cannot have a space.
how to make a variable available to other shells?
export myvar=”value string”
or
myvar =”value string”
export myvar
How to use variable values?
echo $myvar
echo ${myvar}
echo “${myvar}_something”
how to remove a variable?
unset myvar
myvar =
(if we leave blank a variable after equal sign, we unset it)
how to test if a variable is set or not?
[[ -v myvar ]];
echo $?
Return codes:
0: success (variable myvar is set)
1: failure (variable myvar is not set)
[[ -z ${myvar + x} ]];
works opposite to ‘-v’ command above. If var is available, it will set the value
How to print variable value when set or some other value if not set?
echo ${myvar:-“default”}
if myvar is set then displays its value. If not set, then displays default value
echo ${myvar:=”default”}
If myvar is set then displays myvar else sets myvar to defalut value and displays its new value
How to reset value if variable is set?
echo ${myvar:+”default”}
If myvar is set then set the default value and display the new value else display null.
How to find the list of variables stored in the memory?
echo ${!H*}
List of names of shell variables that start with H
how to find the length of the string value of the variable?
echo ${#myvar}
displays length of the string value myvar. If myvar is not set it displays 0
how to get a slice of the string value?
echo ${myvar:5:4}
displays 4 charcters starting from 5th position
How to remove matching pattern
echo ${myvar#pattern} - match once and remove
echo ${myvar##pattern} - match max possible times and remove
how to keep matching pattern within a variable?
echo ${myvar%pattern} -once
${myvar%%pattern} - multiple times
how to match and replace a pattern ?
echo ${myvar/pattern/string} - match once and replace with string.
echo ${myvar//pattern/string} - match max possible &replace with string
how to replace matching pattern by location/
echo ${myvar/#pattern/string}
-match at beginning and replace with string
echo${myvar/%pattern/string}
-match at the end and replace with string
how to change case of the variable?
echo ${myvar,} - change first char to lower case
echo ${myvar,,} - change all chars to lower case
echo ${myvar ^} - change first char to upper case
echo ${myvar ^^} -change all chars to upper case.