Introduction
Testing scripts helps find mistakes early and makes sure they work as expected before using them for real tasks.
# Run script with bash -x for debugging bash -x script.sh # Use shellcheck to find common mistakes shellcheck script.sh # Run script and check exit status ./script.sh if [ $? -eq 0 ]; then echo "Success" else echo "Failure" fi
bash -x to see each command as it runs, which helps find where errors happen.shellcheck tool to catch common script mistakes before running.bash -x myscript.sh
shellcheck myscript.sh
./myscript.sh if [ $? -eq 0 ]; then echo "Script ran successfully" else echo "Script failed" fi
#!/bin/bash # Simple script to greet user name="$1" if [ -z "$name" ]; then echo "No name provided" exit 1 fi echo "Hello, $name!" exit 0
bash -x) to see what happens inside the script.bash -x and shellcheck for easy testing.-x option runs the script showing each command before execution.-v prints shell input lines, -e exits on error, -c runs commands from string.bash -x test.sh? #!/bin/bash x=5 if [ $x -gt 3 ]; then echo "Greater" else echo "Smaller" fi
-x prints each command with a plus sign before executing it.x=5, the test [ $x -gt 3 ], and echo "Greater" are printed before output.#!/bin/bash filename="myfile.txt" if [ -f $filename ] then echo "File exists" else echo "File missing" fi
$filename is unquoted, which can cause errors if it contains spaces.$?$? confirms correct behavior automatically.$? [OK]Pass the test and this pattern moves unknown