Linux Shell Scripting 3 — Questions and Answers
Question 1: In bash, which operator tests whether a string is non-empty?
- [ -z "$var" ]
- [ -n "$var" ] (Correct answer)
- [ -e "$var" ]
- [ -s "$var" ]
Correct answer: [ -n "$var" ]
`-n` returns true if the string length is nonzero; `-z` tests for empty string.
Question 2: What will `echo ${#myvar}` print if `myvar="hello"`?
- hello
- 5 (Correct answer)
- $myvar
- 0
Correct answer: 5
`${#varname}` expands to the length (number of characters) of the variable's value.
Question 3: Which line should appear at the very top of a bash script to specify the interpreter?
- # bash
- #!/bin/bash (Correct answer)
- #!bash
- // !/bin/bash
Correct answer: #!/bin/bash
The shebang `#!/bin/bash` tells the kernel which interpreter to use when the script is executed directly.
Question 4: How do you pass the value of variable `name` to a script as its first argument and access it inside?
- ./script.sh $name; access as $0
- ./script.sh "$name"; access as $1 (Correct answer)
- ./script.sh name; access as $name
- ./script.sh $name; access as ${name}
Correct answer: ./script.sh "$name"; access as $1
Arguments are passed on the command line and accessed inside the script as positional parameters `$1`, `$2`, etc.
Question 5: What is the effect of `trap 'rm -f /tmp/tmpfile' EXIT` in a script?
- Deletes the file only if the script exits with an error
- Runs the cleanup command whenever the script exits for any reason (Correct answer)
- Prevents the script from exiting until the file is removed
- Traps the EXIT signal and ignores it
Correct answer: Runs the cleanup command whenever the script exits for any reason
`trap CMD EXIT` registers a command to run automatically whenever the script exits, enabling reliable cleanup.
Question 6: Which bash feature allows `case "$var" in pattern) ... esac` to match multiple patterns?
- Separate them with &&
- Separate them with | (Correct answer)
- Separate them with ,
- Separate them with ;
Correct answer: Separate them with |
In a `case` statement, the `|` character separates alternative patterns for the same block.
Question 7: What does `read -r line` do differently from `read line` in bash?
- Reads from a file instead of stdin
- Prevents backslash from being treated as an escape character (Correct answer)
- Reads only a single character
- Reads the line in reverse order
Correct answer: Prevents backslash from being treated as an escape character
The `-r` flag disables backslash interpretation, so backslashes are read literally — essential for reading file paths.
In bash, which operator tests whether a string is non-empty?