Posted: . At: 11:19 AM. This was 8 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.

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

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.