Bash: functions and arrays
Declaring and calling a function, variable scope with local, return versus echo, indexed and associative arrays and reading options with getopts: predicting what a script prints.
- 32 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Bash function: what is it?
Show the answer
A named group of commands, declared with
name() { … }, which receives its arguments in$1,$2,$#and$@and is called like a command.The function's parameters hide the script's own for the length of the call:
$1inside the function is not the script's$1.What does this script print?
```bash
f() { local x=2; y=3; }
x=1; y=1
f
echo $x $y`1 32 31 12 1
Show the answer
1 3xis local: the call does not touch the script'sx, which stays at 1.yis assigned withoutlocal, so it is global: it becomes 3.In a Bash function, the … keyword limits a variable to the length of the call; without it, the assignment is ….
Show the answer
In a Bash function, the local keyword limits a variable to the length of the call; without it, the assignment is global.
f() { local x=2; y=3; }: after the call,xkeeps its earlier value andyis 3.Local variable: what is it?
Show the answer
A variable declared with
localinside a function: it exists only during the call and leaves a variable of the same name elsewhere alone.Without
local, every assignment inside a function is global: it overwrites the calling script's variable, for instance a loop counteri.A function that was supposed to hand back a file name ends with
return $name. Running it printsreturn: rapport.txt: numeric argument required. Which fix is right?- Write
return "$name"in double quotes - Write
echo "$name"and capture it withf=$(file_name) - Declare the variable
namewithlocalbefore thereturn - Write
return 0instead, then read$?
Show the answer
Write
echo "$name"and capture it withf=$(file_name)returnonly accepts a number: quotes change nothing, nor doeslocal.return 0would lose the name. The function's output is the right channel for a text.- Write