
Understanding Exit Status in Bash
Every command you run returns an exit status:0means success- Any nonzero value indicates failure
$? always holds the exit status of the last executed command:
Use
echo $? immediately after a command to capture its exit status—subsequent commands will overwrite this value.Exploring Common Special Shell Variables
Here’s a quick reference for the most widely used POSIX-compliant special parameters:| Variable | Description | Example |
|---|---|---|
$* | All positional parameters as a single word | echo "Args: $*" |
$# | Number of positional parameters | echo "Count: $#" |
$0 | Name of the script or shell | echo "Script: $0" |
$! | PID of the last background command | sleep 30 & then echo $! |
$- | Current shell options (flags) as a string | echo "Options: $-" |
Expanding
$* without quotes can lead to word splitting and unintended globbing. Use quotes or consider $@ when preserving argument boundaries is critical.Practical Use Cases
- Argument Validation
- Logging Script Name
- Background Job Monitoring