Variables Flashcards

1
Q

Setting a variable

A

>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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Calling a variable

A

>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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Making an environmental variable available for other scripts

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Deleting/ erasing a variable

A

>unset myvar

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Manipulating a string variable

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

In a script what is referred to when stating ${1} or its sidekick ${1%.*}

A
  • 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}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Referring to command line arguments inside a script

A

!/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 $@
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What’s a loop control variable

&

How is it set

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly