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?

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

Ad