Bash Scripting - BasicsYou want to create a script that accepts a filename as argument and prints "File exists" if it exists. Which script snippet is correct?A#!/bin/bash if [ -f "$1" ]; then echo "File exists" fiB#!/bin/bash if [ $1 ]; then echo "File exists" fiC#!/bin/bash if [ -d "$1" ]; then echo "File exists" fiD#!/bin/bash if [ "$1" == "file" ]; then echo "File exists" fiCheck Answer
Step-by-Step SolutionSolution:Step 1: Understand file existence test in bashUse -f to check if a regular file exists at the path given by $1.Step 2: Identify correct conditional syntax#!/bin/bash if [ -f "$1" ]; then echo "File exists" fi correctly uses [ -f "$1" ] to test file existence and prints message.Final Answer:#!/bin/bash\nif [ -f "$1" ]; then\necho "File exists"\nfi -> Option AQuick Check:Check file existence with -f and $1 argument = #!/bin/bash if [ -f "$1" ]; then echo "File exists" fi [OK]Quick Trick: Use [ -f "$1" ] to test if file exists in bash [OK]Common Mistakes:MISTAKESUsing -d which checks directoriesNot quoting $1 causing errorsComparing $1 to string 'file' incorrectly
Master "Basics" in Bash Scripting9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Bash Scripting Quizzes Bash Scripting Basics - Shebang line (#!/bin/bash) - Quiz 3easy Conditionals - if-then-fi structure - Quiz 11easy Conditionals - Integer comparisons (-eq, -ne, -gt, -lt, -ge, -le) - Quiz 11easy Conditionals - if-elif-else - Quiz 11easy Conditionals - [[ ]] extended test - Quiz 13medium Conditionals - String comparisons (=, !=, -z, -n) - Quiz 7medium Quoting and Expansion - Why quoting rules prevent errors - Quiz 2easy Quoting and Expansion - Backticks and $() for command substitution - Quiz 15hard User Input - Default values for input - Quiz 1easy User Input - read command - Quiz 1easy