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

Take your Linux skills to the next level!

How Linux Works

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

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

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

Ad