010-160 Basic Scripting Concepts 2 — Questions and Answers
Question 1: Which shell built-in command is used to read a line of input from the user and store it in a variable?
- input
- read (Correct answer)
- get
- scan
Correct answer: read
The `read` built-in reads a line from standard input and assigns it to the named variable.
Question 2: What does the following condition test in a bash `if` statement: `[ -f /etc/hosts ]`?
- Whether /etc/hosts is a directory
- Whether /etc/hosts exists and is a regular file (Correct answer)
- Whether /etc/hosts is executable
- Whether /etc/hosts is empty
Correct answer: Whether /etc/hosts exists and is a regular file
The `-f` file test operator returns true when the path exists and is a regular file.
Question 3: In bash, what is the value of `$?` after a command exits successfully?
- 1
- 0 (Correct answer)
- -1
- 255
Correct answer: 0
`$?` holds the exit status of the last command; 0 conventionally means success.
Question 4: Which of the following correctly defines a shell function named `greet`?
- function greet[] { echo Hello; }
- greet() { echo Hello; } (Correct answer)
- def greet() { echo Hello; }
- func greet { echo Hello; }
Correct answer: greet() { echo Hello; }
The POSIX-compatible syntax `name() { commands; }` defines a shell function.
Question 5: What arithmetic value does `$(( 3 ** 2 ))` evaluate to in bash?
- 6
- 9 (Correct answer)
- 32
- 5
Correct answer: 9
The `**` operator performs exponentiation, so 3 to the power of 2 equals 9.
Question 6: Which command would you use inside a script to terminate with exit code 2?
- quit 2
- return 2
- exit 2 (Correct answer)
- stop 2
Correct answer: exit 2
The `exit` command ends the script and passes its numeric argument as the exit status.
Question 7: What does a `#!` (shebang) line at the top of a script specify?
- The script author's name
- A comment describing the script's purpose
- The interpreter used to execute the script (Correct answer)
- The shell variables to export
Correct answer: The interpreter used to execute the script
The shebang (`#!`) followed by a path tells the kernel which interpreter to use to run the script.
Which shell built-in command is used to read a line of input from the user and store it in a variable?