Variables Flashcards
Setting a variable
>myvar=’This is my variable!’
- Note no spaces before or after the = sign
- Note use of ‘ instead of “
- Note that this makes the variable exclusively available to shell script
Calling a variable
>echo $myvar
- Note the use of $
>echo foo${myvar}crap
fooThis is my variable!crap #
- Note the use of { } to specify the variable when spaces are not available
Making an environmental variable available for other scripts
- You need to export the variable after creating it so that it is available to all scripts. Remember that defining it only makes it available to shell scripts.
> export myvar
- Or you can define and export the variable in one line
>export myvar=’this is my variable!’
- Note that the export command does not work from inside a script
Deleting/ erasing a variable
>unset myvar
Manipulating a string variable
- To extract and display parts of a variable you need to use the ${ } notation to specify variable and manipulation details.
>myvar=’this is my variable’
>echo ${myvar:0:4}
this
- Variable expansion is the replacement of the variable by its value
In a script what is referred to when stating ${1} or its sidekick ${1%.*}
- This refers to the environmental varaible that is fed to the script as its first argument in the command line
>./myscript.sh balls bucket
- here if the second argument needs to be referred to in the script it will appear as ${2} Or if manipulated ${2:0:4}
Referring to command line arguments inside a script
!/usr/bin/env bash
echo name of script is $0
echo first argument is $1
echo second argument is $2
echo seventeenth argument is ${17}
echo number of arguments is $#
echo list of all my arguments is $@
- $0 by default yields the name of the script
- from the 10th argument onwards the argument number needs to be in brackets, hence ${17}
- the number of arguments fed to the script can be called by $#
- List of all arguments passed to script is called by $@
What’s a loop control variable
&
How is it set
Answer is two in one.
The loop control variable is set inside the loop itself and its value is used to control the loop operation.
#!/usr/bin/env bash for **x** in one two three four
do
echo number $x
done
output:
number one
number two
number three
number four