Variable naming conventions:
Only letters (a to z or A to Z), numbers (0 to 9), and the underscore character ( _) can be used in a variable’s name in Linux scripting.
Example of some valid variable names:
name, Name, fullName, full_name, _name, name0, name1, name01, NAME, VAR, _VAR
Example of some invalid variable names:
!name, -name, full-name, name!, name*, 1name, 1_name
Here one thing to mention that Bash/Shell variables are case sensitive. Name, name, or NAME will be treated as three different variable names.
Define and use variables:
Use/access a defined variable, dollar sign ($) is used :
newValue=$VALUE echo $VALUE
Note: Space is not allowed in either sides of the equal sign.
Save this code as variable_eample.sh
#!usr/bin/env bash #space is not allowed in either sides of the equal sign name=Olive colour=Green echo Colour of $name is $colour. #String cannot have space inside, use quatation mark to degine a string full_name="Green Olive" echo $full_name
Run in a Linux terminal and you will see the output like:
$ bash variable_eample.sh Output: Colour of Olive is Green. Green Olive
If a variable is marked as “readonly” its value cannot be changed/updated later. We can use readonly variables to define constants. Example:
#!/bin/sh # readonly variable FIXED_VAL=10000 readonly FIXED_VAL echo value is: $FIXED_VAL FIXED_VAL=20000 # Cannot be changed, will give error : FIXED_VAL: readonly variable
We can unset a variable using the “unset” keyword. If we use unset on a variable, the shell removes it from the list of variables it keeps track of. We can’t access the value in a variable after it’s been unset. Example:
!/bin/sh # unsetting variable OLD_NAME="Akbar" unset OLD_NAME echo $OLD_NAME # this will print nothing as it was unset
Visit GitHub repository for details examples.