|
| 1 | +# Have Script ShellCheck Itself When Executing |
| 2 | + |
| 3 | +The [ShellCheck](https://www.shellcheck.net/) utility can be run against bash |
| 4 | +scripts to check if there are any warnings or errors we should fix. It works |
| 5 | +great as long as we remember to run it. |
| 6 | + |
| 7 | +I wondered if I could make it easier on myself by not having to remember to run |
| 8 | +it. What if my bash script were to `shellcheck` itself? |
| 9 | + |
| 10 | +Here is an example script where at the beginning it looks for and runs the |
| 11 | +`shellcheck` utility against `$0` (the path of the script). This is kind of |
| 12 | +meta. As the script is executing, it has an external program run against the |
| 13 | +entire contents of itself. If there are any `shellcheck` issues, they get |
| 14 | +displayed and the program exits early. |
| 15 | + |
| 16 | +```bash |
| 17 | +#!/bin/bash |
| 18 | + |
| 19 | +# Exit immediately if any command fails |
| 20 | +set -e |
| 21 | + |
| 22 | +# Self-validation using ShellCheck |
| 23 | +if command -v shellcheck &> /dev/null; then |
| 24 | + echo "Validating script with ShellCheck..." |
| 25 | + |
| 26 | + # $0 refers to the script itself |
| 27 | + if ! shellcheck "$0"; then |
| 28 | + echo "ShellCheck found issues in the script. Exiting." |
| 29 | + exit 1 |
| 30 | + fi |
| 31 | + echo "Script validation passed." |
| 32 | +else |
| 33 | + echo "Warning: ShellCheck not found. Skipping validation." |
| 34 | +fi |
| 35 | + |
| 36 | +echo "Script execution continuing..." |
| 37 | + |
| 38 | +# shellcheck warning here |
| 39 | +read -p "Continue with current operation? (yes/no): " CONTINUE_WITH_EXISTING |
| 40 | +if [[ ! "$CONTINUE_WITH_EXISTING" =~ ^[Yy][Ee][Ss]$ ]]; then |
| 41 | + echo "Operation cancelled." |
| 42 | + exit 1 |
| 43 | +fi |
| 44 | +``` |
| 45 | + |
| 46 | +This last bit of the script with the `read` command will trigger a warning from |
| 47 | +`shellcheck`. |
| 48 | + |
| 49 | +```bash |
| 50 | +$ ./check.sh |
| 51 | +Validating script with ShellCheck... |
| 52 | + |
| 53 | +In ./check.sh line 23: |
| 54 | +read -p "Continue with current operation? (yes/no): " CONTINUE_WITH_EXISTING |
| 55 | +^--^ SC2162 (info): read without -r will mangle backslashes. |
| 56 | + |
| 57 | +For more information: |
| 58 | + https://www.shellcheck.net/wiki/SC2162 -- read without -r will mangle backs... |
| 59 | +ShellCheck found issues in the script. Exiting. |
| 60 | +``` |
0 commit comments