Skip to content

Instantly share code, notes, and snippets.

@zoolu-got-rhythm
Last active September 17, 2023 20:58
Show Gist options
  • Save zoolu-got-rhythm/8dd634d83ac4fc90202378656b9ac392 to your computer and use it in GitHub Desktop.
Save zoolu-got-rhythm/8dd634d83ac4fc90202378656b9ac392 to your computer and use it in GitHub Desktop.
robust bash function that counts console.log's in a javascript file, options to print lines logs found on aswell
#!/bin/bash
# takes in a file as argument 1
# takes in a boolean as argument 2
count_and_print_logs_in_file() {
file=$1
print_logs_found_on_lines=false
if [ $# -gt 1 ]; then
print_logs_found_on_lines=$2
fi
total_console_logs_found=0
while read -r line; do
line_number_found_on=$(echo "$line" | grep -o -E '\d+')
console_logs_found_on_line=$(echo "$line" | grep -o console | wc -l | tr -d '[:blank:]')
total_console_logs_found=$((total_console_logs_found + console_logs_found_on_line))
if [ "$print_logs_found_on_lines" == true ]; then
if [ "$console_logs_found_on_line" -gt "1" ]; then
echo "$console_logs_found_on_line console.log's found on line $line_number_found_on"
else
echo "$console_logs_found_on_line console.log found on line $line_number_found_on"
fi
fi
done < <(cat "$file" | awk '/console/,/log/{print NR, $0}' | grep -E console) # this approach used instead of piping this into while loop at -
# start (which creates a subshell meaning var's you store globalling from within loop get lost) -
# see: https://www.shellcheck.net/wiki/SC2031 for more info
if [ "$total_console_logs_found" -gt "1" ]; then
echo "total of $total_console_logs_found console.log's found in $file"
else
echo "total of $total_console_logs_found console.log found in $file"
fi
}
# propagate arguments in shell script down into function
count_and_print_logs_in_file "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment