How to manipulate environment variables with the bash shell on Linux.

Posted: May 2, 2016. At: 11:19 AM. This was 2 years ago. Post ID: 9029
Page permalink.
WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters. These cookies expire two weeks after they are set.

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.

[email protected]:~$ echo ${#LOGNAME}
5

Make the first letter of the string in an environment variable uppercase.

[email protected]:~$ echo ${LOGNAME^}
Jason
[email protected]:~$ echo ${LOGNAME^^}
JASON

Find and replace only the first occurrence of a string(s) in a variable.

[email protected]:~$ echo ${LOGNAME/jason/jaden}
jaden

Find and replace all occurrence of a string(s) in a variable.

[email protected]:~$ echo ${LOGNAME//jason/jaden}
jaden

Print an error message when the environment variable is not defined.

[email protected]:~$ echo ${LOGNAME?Variable not defined.}
jason
[email protected]:~$ echo ${LOGNAME2?Variable not defined.}
bash: LOGNAME2: Variable not defined.

If an environment variable is undefined, substitute another value.

[email protected]:~$ echo ${LOGNAME2-Goku}
Goku

Replace the contents of an environment variable unless it is undefined…

[email protected]:~$ echo ${LOGNAME+string}
string

Make all of the letters in the variable lowercase.

[email protected]:~$ echo ${LOGNAME,,}
jason

Make only the first letter in the variable lowercase.

[email protected]:~$ echo ${LOGNAME,}
jason

Extract substring from $string at $position. Length is :length.

${LOGNAME:position:length}

[email protected]op:~$ 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

No comments have been made. Use this form to start the conversation :)

Leave a Reply