View on GitHub

Computational Techniques for Life Sciences

VARIABLES

As we’ve already scene, variables store important shell environment information as well as information we wish to repeat or reuse.

Types of VARIABLES

Variables in bash are most often:

There are a small number of other variable types, but there are NO FLOATING POINT variables.

How to access the value of a variable

The value of a variable can be accessed by preceding it with a $.

prompt> a=apple
prompt> echo $a
apple

Expanded variable access
(a.k.a. parameter substitution)

Surrounding a variable with ${} indicates you want to treat it as a parameter and access more information about the variable.

Three common parameter substitutions are:

Factors affecting parameter substitution

We’ll come back to more parameter substitutions shortly, button let’s explore other factors that impact use of variables.

Quotation and escaping

As we’ve seen, $variable and ${variable} correspond to the value of variable , but how we access that value is important.

double quotes: treat items inside as single element

prompt> a="1 2  3   4    END"
prompt> echo $a
1 2 3 4 END
prompt> echo ${a}
1 2 3 4 END
prompt> echo "${a}"
1 2  3   4    END

QUESTION: Why did only "${a}" show the true value?

single quotes: treat items inside as single element and do not evaluate substitutions

prompt> echo '${a}'
${a}
prompt> echo '${a}' = $a
${a} = 1 2 3 4 END

blackslash(\) (aka escaping): do not evaluate substitutions or other special behaviour.

prompt> echo '${a}' = \$a
${a} = $a

Exercise:

Let’s practice what you’ve learned with some changes:

prompt> cp first_script.sh second_script.sh
prompt> vi second_script.sh

#!/bin/bash
# The first line is a "shebang". This line is a comment.
# Print a message
STRING1='TACC       Summer   Institute'
STRING2="is    great!"
YEAR=2018
echo "${STRING1}${YEAR}" ${STRING2} ${#YEAR}

type <ESC>:wq to write the changes then quit vi.

QUESTION: Do we need to chmod +x ?

No. But why not?

execute

prompt> ./second_script.sh
TACC       Summer   Institute2018 is great! 4

DISCUSS: Why did we observe that pattern of spacing?


Prev BASH scripting | Next Arithmetic | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center