Challenge - 5 Problems
Command-line Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this script with arguments?
Consider the following bash script saved as
args.sh. What will be the output if you run ./args.sh apple banana cherry?Bash Scripting
#!/bin/bash echo "First argument: $1" echo "Second argument: $2" echo "All arguments: $@"
Attempts:
2 left
💡 Hint
Remember that $1 is the first argument, $2 the second, and $@ represents all arguments.
✗ Incorrect
In bash, $1 is the first argument passed to the script, $2 the second, and $@ expands to all arguments separated by spaces.
💻 Command Output
intermediate2:00remaining
What does this script print when no arguments are given?
Given this script
args_empty.sh, what is the output when run as ./args_empty.sh with no arguments?Bash Scripting
#!/bin/bash echo "Argument 1 is: $1" echo "Number of arguments: $#"
Attempts:
2 left
💡 Hint
When no arguments are passed, $1 is empty and $# is zero.
✗ Incorrect
If no arguments are passed, $1 is empty (prints nothing) and $# is 0 indicating zero arguments.
📝 Syntax
advanced2:00remaining
Which option correctly prints the third argument?
You want to print the third command-line argument in a bash script. Which of these lines will do it correctly?
Attempts:
2 left
💡 Hint
Use the positional parameter syntax for arguments.
✗ Incorrect
In bash, $3 prints the third argument. ${3} is invalid syntax. $[3] is arithmetic expansion and prints 3. $@3 is invalid.
🔧 Debug
advanced2:00remaining
Why does this script print empty for $2?
This script is run as
./script.sh one two. Why does it print an empty line for the second argument?Bash Scripting
#!/bin/bash echo "Arg1: $1" echo "Arg2: $ 2"
Attempts:
2 left
💡 Hint
Check the spacing between $ and the number.
✗ Incorrect
In bash, $2 must be written without spaces. Writing $ 2 means $ alone (empty variable) followed by 2 as text, so it prints empty line.
🚀 Application
expert3:00remaining
How many arguments does this script count?
Given this script
count_args.sh, what number will it print when run as ./count_args.sh a "b c" d?Bash Scripting
#!/bin/bash count=0 for arg in "$@"; do count=$((count + 1)) done echo $count
Attempts:
2 left
💡 Hint
Remember that quoted arguments count as one argument.
✗ Incorrect
The script loops over all arguments in "$@" which preserves quoted arguments as single items. The arguments are: a, b c, d → total 3.