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}

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

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

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

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

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

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

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

[email protected]:~$ echo ${LOGNAME?Variable not defined.}
[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}

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

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

Make all of the letters in the variable lowercase.

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

Make only the first letter in the variable lowercase.

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

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


[email protected]op:~$ echo ${LOGNAME:2:3}

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