Przejdลบ do treล›ci

๐Ÿงพ Commands and Exit Codes

Every command returns an exit code that indicates success or failure. Understanding these codes is critical for scripting robust workflows.

๐Ÿ”ข Exit Code Meaning

Exit codes range from 0 to 255. By convention: - 0 = Success - 1โ€“255 = Various types of failures

Check last commandโ€™s exit code with $?:

1
2
3
4
$ ls /nonexistent
ls: cannot access '/nonexistent': No such file or directory
$ echo $?
2


๐Ÿงช Testing Exit Codes in Scripts

Use conditional statements to check results:

1
2
3
4
5
6
7
#!/bin/sh
command_that_might_fail
if [ $? -eq 0 ]; then
    echo "Success!"
else
    echo "Something went wrong."
fi

Or more concisely:

1
2
3
4
5
if command_that_might_fail; then
    echo "Success!"
else
    echo "Failure occurred."
fi


๐Ÿงฐ Common Exit Codes

Code Meaning Examples
0 Success Normal completion
1 General error Misuse of shell builtins
2 Misuse of shell builtin Incorrect usage
126 Command found but not executable Permission denied
127 Command not found Typo or missing PATH entry
130 Script terminated by Ctrl+C Signal SIGINT received

Full list available in sysexits.h or man sysexits.


๐Ÿงช Practical Example

Hereโ€™s how to handle errors gracefully:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/bin/sh

backup_file() {
    cp "$1" "$1.bak"
    return $?
}

backup_file important.conf
if [ $? -ne 0 ]; then
    echo "Backup failed!" >&2
    exit 1
fi
echo "Backup completed."

This ensures failures don't get ignored silently.

๐Ÿ‘‰ Continue to: Path and Executables