Manipulating environment variables in the bash shell is very useful indeed, this shows a few examples. This uses the feature of the Linux shell called parameter expansion. This replaces the name of an environment variable with it`s contents when echoed to the shell.
These few examples show how the content echoed to the terminal may be manipulated to alter the output or replace it entirely.
Get the length of a string in an environment variable.
jason@jason-desktop:~$ echo ${#LOGNAME} 5 |
Make the first letter of the string in an environment variable uppercase.
jason@jason-desktop:~$ echo ${LOGNAME^} Jason |
jason@jason-desktop:~$ echo ${LOGNAME^^} JASON |
Find and replace only the first occurrence of a string(s) in a variable.
jason@jason-desktop:~$ echo ${LOGNAME/jason/jaden} jaden |
Find and replace all occurrence of a string(s) in a variable.
jason@jason-desktop:~$ echo ${LOGNAME//jason/jaden} jaden |
Print an error message when the environment variable is not defined.
jason@jason-desktop:~$ echo ${LOGNAME?Variable not defined.} jason jason@jason-desktop:~$ echo ${LOGNAME2?Variable not defined.} bash: LOGNAME2: Variable not defined. |
If an environment variable is undefined, substitute another value.
jason@jason-desktop:~$ echo ${LOGNAME2-Goku} Goku |
Replace the contents of an environment variable unless it is undefined…
jason@jason-desktop:~$ echo ${LOGNAME+string} string |
Make all of the letters in the variable lowercase.
jason@jason-desktop:~$ echo ${LOGNAME,,} jason |
Make only the first letter in the variable lowercase.
jason@jason-desktop:~$ echo ${LOGNAME,} jason |
Extract substring from $string at $position. Length is :length.
${LOGNAME:position:length}
jason@jason-desktop:~$ echo ${LOGNAME:2:3} son |
Use this example to delete one word from a string contained in an environment variable. This deletes the first match from the left.
jason@darknet:~] export foo="Hello Hoffman, are you ready for your test?" [jason@darknet:~] echo ${foo#Hello } Hoffman, are you ready for your test? |
Delete the first matching string from the right.
[jason@darknet:~] echo ${foo%test?} Hello Hoffman, are you ready for your |