0
0
Bash Scriptingscripting~20 mins

set -x for trace mode in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Trace Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output when using set -x in a simple script?
Consider this bash script snippet:
#!/bin/bash
set -x
x=5
y=3
z=$((x + y))
echo $z

What will be printed to the terminal when this script runs?
Bash Scripting
#!/bin/bash
set -x
x=5
y=3
z=$((x + y))
echo $z
A
+ x=5
+ y=3
+ z=8
8
B8
C
+ x=5
+ y=3
+ z=8
+ echo 8
8
D
x=5
y=3
z=8
echo 8
8
Attempts:
2 left
💡 Hint
Trace mode prints each command with a plus sign before executing it.
💻 Command Output
intermediate
2:00remaining
What happens if set -x is turned off mid-script?
Given this bash script:
#!/bin/bash
set -x
var=10
set +x
var2=20
echo $var $var2

What will be the output including trace lines?
Bash Scripting
#!/bin/bash
set -x
var=10
set +x
var2=20
echo $var $var2
A
+ var=10
var2=20
10 20
B
+ var=10
+ set +x
+ var2=20
+ echo 10 20
10 20
C
var=10
var2=20
10 20
D
+ var=10
var2=20
+ echo 10 20
10 20
Attempts:
2 left
💡 Hint
set +x disables trace mode, so commands after it won't show trace.
🔧 Debug
advanced
2:00remaining
Why does this script not show trace output after set -x?
Look at this script:
#!/bin/bash
set -x
if false; then
  echo "Won't run"
fi
set +x
echo "Done"

Why is there no trace output for the echo inside the if block?
Bash Scripting
#!/bin/bash
set -x
if false; then
  echo "Won't run"
fi
set +x
echo "Done"
ABecause the if condition is false, the echo inside never runs, so no trace output.
BBecause set -x only traces commands outside if blocks.
CBecause set -x was disabled before the if block.
DBecause echo commands are never traced.
Attempts:
2 left
💡 Hint
Trace shows commands that actually run.
💻 Command Output
advanced
2:00remaining
What is the output of this script with nested set -x and set +x?
Analyze this script:
#!/bin/bash
set -x
var=1
{
  set +x
  var=2
  echo $var
}
echo $var

What is the full output including trace lines?
Bash Scripting
#!/bin/bash
set -x
var=1
{
  set +x
  var=2
  echo $var
}
echo $var
A
+ var=1
var=2
2
+ echo 2
2
B
+ var=1
var=2
2
+ echo 2
+ echo 2
1
C
+ var=1
var=2
2
+ echo 2
+ echo 2
2
D
+ var=1
var=2
2
+ echo 2
+ echo 2
+ echo 2
2
Attempts:
2 left
💡 Hint
set +x disables trace inside the block, but echo outside still traces.
🧠 Conceptual
expert
2:00remaining
How does set -x help in debugging complex scripts?
Which of these best explains the main benefit of using set -x in bash scripts?
AIt automatically fixes syntax errors in the script.
BIt shows each command and its arguments as they are executed, helping to trace script flow and spot errors.
CIt runs the script faster by optimizing commands.
DIt hides sensitive information from the output.
Attempts:
2 left
💡 Hint
Think about what trace mode does when enabled.