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?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

System Admin Handbook

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

This book approaches system administration in a practical way and is an invaluable reference for both new administrators and experienced professionals. It details best practices for every facet of system administration, including storage management, network design and administration, email, web hosting, scripting, and much more.

$ Check price
74.9974.99Amazon 4.5 logo(142+ reviews)

More Linux & UNIX resources

Ad