Last active
October 22, 2021 13:58
-
-
Save nweldev/f1b8b46082c48fbdeec3c9cbcbe6d0da to your computer and use it in GitHub Desktop.
Lint Unix shell scripts (with autofix)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
## Usage: shellcheck.sh [fix] [path to file] | |
# name of all the directories that should be ignored | |
IGNORED_DIR_NAMES=("node_modules" "venv" "reports") | |
# find options for ignoring directories | |
IGNORE_PARAM=$(for i in "${!IGNORED_DIR_NAMES[@]}"; do | |
echo -n "-name ${IGNORED_DIR_NAMES[$i]} "; | |
if [[ "$i" -ne "${#IGNORED_DIR_NAMES[@]}-1" ]]; then | |
echo -n "-o "; | |
fi | |
done) | |
# path to the shellcheck executable | |
shellcheck="$(which shellcheck)" | |
### $ shellcheck.sh | |
### Check every .sh file in the current directory | |
# shellcheck disable=SC2154 | |
if [ -z "$1" ]; then | |
# shellcheck disable=SC2046,SC2206,SC2086 | |
${shellcheck} -x $(find . -type d \( ${IGNORE_PARAM} \) -prune -o -name '*.sh' -print) | |
### $ shekkcheck.sh fix [filepath] | |
### Autofix | |
elif [ "$1" == "fix" ]; then | |
#### $ shellcheck.sh fix | |
#### Autofix every .sh file in the current directory | |
if [ -z "$2" ]; then | |
# Use all the available processing units (cf. man nproc) to execute each shellcheck command in parallel | |
PROC_LIMIT="$(nproc)" | |
# shellcheck disable=SC2038,SC2068,SC2086,SC2140 | |
find . \ | |
-type d `# As we use "-prune", we have to start with this to exclude directories based on there names.` \ | |
\( ${IGNORE_PARAM} \) `# Groups operations (to exclude directories).` \ | |
-prune `# Use "-prune" instead of "-not" for performance (avoid to evaluate the expression for each node.` \ | |
-o -type f -iname "*.sh" \ | |
-printf '%P ' `# By default, "-type d" will give paths starting with "./", but "git apply" doesn't like that, so we need to remove those.` | | |
qxargs -0 -I {} -P "${PROC_LIMIT}" \ | |
bash -c "${shellcheck} -x -f diff "{}" | git apply" # output shellcheck feedbacks as a git patch | |
#### $ shellcheck.sh fix <filepath> | |
#### Autofix a single file | |
else | |
${shellcheck} -x -f diff "$2" | git apply | |
fi | |
### $ shellcheck.sh <filepath> | |
### Check a single file | |
elif [ -n "$1" ]; then | |
${shellcheck} -x "$1" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment