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?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

Command Line Kung Fu

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

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Ad