We are able to declare and use variables within the shell.
[user@host ~]$ var1='hello'
[user@host ~]$ echo $var1 world!
hello world!
When assigning a variables do not include spaces either side of the ‘=’ sign. Declared variables can be referenced using the ‘$’ sign and their name.
[user@host ~]$ myname="John Smith"
[user@host ~]$ echo "Hello my name is $myname. Nice to meet you."
Hello my name is John Smith. Nice to meet you.
[user@host ~]$ echo 'Hello my name is $myname. Nice to meet you.'
Hello my name is $myname. Nice to meet you.
When using double quotes, bash will scan the contents and expand any variables.
Look at the example below:
[user@host ~]$ fruit=orange
[user@host ~]$ echo "I love eating $fruits."
I love eating .
because of the s, bash thinks the variable name is fruits.
In some cases we need to surround a variable name with braces.
[user@host ~]$ echo "I love eating ${fruit}s."
I love eating oranges.
[user@host ~]$ two=2
[user@host ~]$ result=$(( $two + 2 ))
[user@host ~]$ echo $result
4
[user@host ~]$
Integer arithmetic can be done inside $(( ))
Run commands inside $( ) and assign the wrapped command to a variable.
[user@host ~]$ ls
a_directory a_file
[user@host ~]$ dir_contents=$( ls )
[user@host ~]$ echo $dir_contents
a_directory a_file
What is the output of this command?
[user@host ~]$ echo $PATH
Note the structure: <path1>:<path2>:<path3>
PATH is an environment variable which Bash uses to search for commands typed on the command line without a full path.
Use the command env to discover more environment variables.
Next activity: Reading - Finding Loops.