0
0
Bash Scriptingscripting~20 mins

Command-line arguments ($1, $2, ...) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Command-line Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2: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: $@"
A
First argument: apple
Second argument: cherry
All arguments: apple banana cherry
B
First argument: banana
Second argument: cherry
All arguments: apple banana cherry
C
First argument: apple
Second argument: banana
All arguments: apple banana cherry
D
First argument: apple
Second argument: banana
All arguments: apple
Attempts:
2 left
💡 Hint
Remember that $1 is the first argument, $2 the second, and $@ represents all arguments.
💻 Command Output
intermediate
2: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: $#"
A
Argument 1 is: null
Number of arguments: 0
B
Argument 1 is: $1
Number of arguments: 1
C
Argument 1 is: 
Number of arguments: 1
D
Argument 1 is: 
Number of arguments: 0
Attempts:
2 left
💡 Hint
When no arguments are passed, $1 is empty and $# is zero.
📝 Syntax
advanced
2: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?
Aecho $3
Becho $[3]
Cecho ${3}
Decho $@3
Attempts:
2 left
💡 Hint
Use the positional parameter syntax for arguments.
🔧 Debug
advanced
2: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"
ABecause $2 is not set when two arguments are passed.
BBecause there is a space between $ and 2, so $ is treated as variable and 2 as text.
CBecause $ 2 is correct syntax but the second argument is empty.
DBecause the script needs quotes around $2 to print it.
Attempts:
2 left
💡 Hint
Check the spacing between $ and the number.
🚀 Application
expert
3: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
A3
B4
C1
D5
Attempts:
2 left
💡 Hint
Remember that quoted arguments count as one argument.