Introduction
Exit codes tell us if a command worked or failed. They help scripts decide what to do next.
echo $? # shows the exit code of the last commandls /tmp echo $?
ls /not_exist echo $?
mkdir newfolder echo $?
#!/bin/bash mkdir testfolder if [ $? -eq 0 ]; then echo "Folder created successfully." else echo "Failed to create folder." fi rm -r testfolder if [ $? -eq 0 ]; then echo "Folder removed successfully." else echo "Failed to remove folder." fi
0 usually mean in bash scripting?$? holds the exit code of the last command.echo $? prints the exit code correctly.ls /nonexistent_dir echo $?
ls /nonexistent_dir tries to list a folder that does not exist, so it fails.$? holds a non-zero exit code, 2 for ls missing directories.mkdir test_dir false if [ $? -eq 0 ]; then echo "Created" else echo "Failed" fi
$? must be checked immediately after the command it relates to.mkdir and checking $?, the exit code changes.cmd1 and cmd2. You want to run cmd2 only if cmd1 succeeded (exit code 0). Which is the best way to do this?&& runs the second command only if the first succeeds (exit code 0).cmd1 && cmd2 which is concise and reliable for this purpose.Pass the test and this pattern moves unknown