0
0
Bash Scriptingscripting~20 mins

Special variables ($0, $1, $#, $@, $?, $) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Special Variables 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?
Consider this bash script saved as test.sh and run as ./test.sh apple banana:
echo "$0"
echo "$1"
echo "$#"
echo "$@"
echo "$$"

What will be the output?
Bash Scripting
echo "$0"
echo "$1"
echo "$#"
echo "$@"
echo "$$"
A
./test.sh
apple
3
apple banana
<process_id>
B
test.sh
banana
2
apple banana
<process_id>
C
./test.sh
apple
2
apple banana
<process_id>
D
./test.sh
banana
1
banana
<process_id>
Attempts:
2 left
💡 Hint
Remember $0 is the script name, $1 is the first argument, $# is the number of arguments, $@ is all arguments, and $$ is the current process ID.
💻 Command Output
intermediate
1:30remaining
What does $? represent after a command?
In bash, after running a command, what does the special variable $? hold?

Example:
ls /nonexistent
 echo $?
Bash Scripting
ls /nonexistent
 echo $?
AThe name of the script
BThe exit status of the last command (0 if success, non-zero if failure)
CThe number of arguments passed to the script
DThe process ID of the last command
Attempts:
2 left
💡 Hint
$? tells if the last command worked or not.
💻 Command Output
advanced
1:00remaining
How many arguments are passed to this script?
Given this script run as ./script.sh one two three:
echo $#

What is the output?
Bash Scripting
echo $#
A3
B4
C1
D0
Attempts:
2 left
💡 Hint
$# counts how many arguments are given to the script.
💻 Command Output
advanced
1:30remaining
What is the output of this script using $@ and $*?
Consider this script run as ./script.sh a b c:
echo "$@"
echo "$*"

What is the output?
Bash Scripting
echo "$@"
echo "$*"
A
a b c
"a b c"
B
"a" "b" "c"
a b c
C
"a b c"
a b c
D
a b c
a b c
Attempts:
2 left
💡 Hint
$@ and $* behave differently when quoted.
💻 Command Output
expert
1:30remaining
What is the value of $$ inside a script?
In a bash script, what does the special variable $$ represent?

Example:
echo $$
Bash Scripting
echo $$
AThe process ID of the current shell running the script
BThe number of arguments passed to the script
CThe exit status of the last command
DThe name of the script
Attempts:
2 left
💡 Hint
$$ is related to the process running the script.