Linux Shell Scripting 4 — Questions and Answers
Question 1: Which bash arithmetic syntax correctly increments a variable `count`?
- count = count + 1
- ((count++)) (Correct answer)
- count += 1
- $count++
Correct answer: ((count++))
`(( ))` is bash's arithmetic evaluation context, where C-style expressions like `count++` are valid.
Question 2: What does the `-f` flag test for in `[ -f filename ]`?
- File exists and is a directory
- File exists and is a regular file (Correct answer)
- File exists and is executable
- File exists and is not empty
Correct answer: File exists and is a regular file
`-f` checks that the path exists and is a regular file (not a directory or device).
Question 3: How does `while IFS= read -r line; do ...; done < file.txt` work?
- Reads file.txt line by line, stripping leading/trailing whitespace
- Reads file.txt line by line, preserving whitespace and backslashes (Correct answer)
- Appends each line to a variable named line
- Reads the file in binary mode
Correct answer: Reads file.txt line by line, preserving whitespace and backslashes
Setting `IFS=` prevents whitespace stripping and `-r` prevents backslash processing, giving raw lines.
Question 4: What is the result of `echo "${var:-default}"` when `var` is unset?
- Prints nothing
- Prints 'default' (Correct answer)
- Prints '$var'
- Causes an error
Correct answer: Prints 'default'
`${var:-default}` expands to `default` if `var` is unset or empty, without modifying `var`.
Question 5: Which command within a script will print the script's own filename?
- echo $0 (Correct answer)
- echo $1
- echo $$
- echo $SCRIPT
Correct answer: echo $0
`$0` holds the name or path of the running script (or the shell name if running interactively).
Question 6: What happens when you use `local varname` inside a bash function?
- Exports the variable to child processes
- Restricts the variable's scope to that function (Correct answer)
- Makes the variable read-only
- Converts the variable to an array
Correct answer: Restricts the variable's scope to that function
`local` limits a variable's visibility to the function (and its children), preventing pollution of the global scope.
Question 7: Which construct runs `cmd2` only if `cmd1` succeeds?
- cmd1 || cmd2
- cmd1 && cmd2 (Correct answer)
- cmd1 ; cmd2
- cmd1 | cmd2
Correct answer: cmd1 && cmd2
`&&` is the AND operator; `cmd2` executes only if `cmd1` exits with status 0.
Which bash arithmetic syntax correctly increments a variable `count`?