02. Manipulating Variables

Here are a few ways to find and change the properties of variables.

Length of a variable

To find the length of a variable, precede the variable name with a #.

$ test=abcdefghijklmnopqrstuvwxyz
$ echo ${#test}
26

Finalizing variables

To make a variable constant, or read-only, we can use the readonly command. This forbids any further assignments to them.

$ test='Hello world!'
$ echo $test
Hello world!
$ readonly test
$ test='Hi Mars!'
-bash: test: readonly variable

Making variables persist

Variables created will only be available to the current shell - any child shells (subshells) spawned will not inherit them. To make it available to any subshells, we use the export command.

The export command places the variables onto the environment.

$ secret_message='Meet me at the treehouse at 4:32pm'
$ other_message='Do not meet me at the treehouse at 4:32pm'
$ export secret_message
$ bash
# spawn a new child (subshell)
$ echo $secret_message
Meet me at the treehouse at 4:32pm
$ echo $other_message
# no output
 
$ exit

Unsetting variables

To remove a value from a variable, use the unset command.

$ unset my_age
$ echo $my_age
# no output

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

Linux for Beginners

Take your Linux skills to the next level! Try Linux & UNIX

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Ad