Explore your understanding of Bash variables, loop structures, and functions, crucial elements in the tools ecosystem for creating effective CLI utilities. Enhance your skills by identifying best practices, syntax, and common pitfalls in Bash scripting related to these core components.
Which line correctly assigns the string value 'world' to the variable GREETING in a Bash script?
Explanation: In Bash, variable assignment requires no spaces around the equals sign, thus 'GREETING=world' is correct. The option 'GREETING == 'world'' uses a comparison operator which is incorrect for assignment. 'GREETING: world' is not a valid assignment syntax in Bash. 'var GREETING = 'world'' follows syntax from other programming languages but is invalid in Bash.
How would you iterate over each filename in the current directory using a Bash for loop?
Explanation: The syntax 'for file in *; do echo $file; done' is the correct Bash method for looping through filenames. 'for file of * { echo $file }' uses incorrect syntax and braces. 'foreach file [*]; print $file; end' is not recognized in Bash, though similar in other shells. 'loop file from *: print($file)' uses invalid keywords and syntax for Bash.
Which statement properly defines a function named 'showDate' that displays the current date in Bash?
Explanation: The correct way in Bash is 'showDate() { date; }' which defines the function and its command block. 'def showDate() { date }' and 'function showDate: { date }' use keywords or symbols not used in Bash. 'showDate = function() { date; }' mixes up styles from other programming languages and is not valid Bash syntax.
In Bash scripting, how can a function named 'printMsg' access its first argument when called as 'printMsg Hello'?
Explanation: The special variable '$1' inside a Bash function refers to the first positional argument given to the function. 'arg1' and 'msg' are not automatically set in Bash functions. 'function[1]' is not a valid way to access arguments in Bash. Only '$1', '$2', etc., are used for function arguments.
If you want to immediately skip to the next iteration in a Bash 'while' loop upon a certain condition, which keyword should you use?
Explanation: The 'continue' keyword tells the Bash loop to skip all remaining commands in the current iteration and proceed to the next cycle. Using 'exit' will terminate the entire script, not just the current loop iteration. There are no 'skip' or 'next' keywords in Bash for this purpose, making them invalid.