Why you should care
The $# variable indicates the number of arguments. If this variable is improperly implemented, then the arguments are left unchecked which can lead to improper execution and bugs in the code.
Leaving arguments unchecked on multiple shell scripts can be a blow to the overall portfolio. This can cause productivity issues in an agile-based environment where some developers are trying to debug their code but end up over-complicating the process and leaving other developers without any progress to work towards.
CAST recommends checking arguments by adding spaces between its arguments like the following example below –
if [$# -ne 1]; then echo "illegal number of parameters" fi
if [ "$#" -ne 1 ]; then echo "Illegal number of parameters" fi
Instead of leaving arguments unchecked, they can be removed by adding shift like the following example below –
if (( $# < 3 )); then echo "$0 old_string new_string file [file...]" exit 0 else ostr="$1"; shift nstr="$1"; shift fi
These errors usually occur because the style-guide in the company is not followed by development teams or has not been updated for future projects. For more help on checking arguments, refer to “Scripting Guide for Bash”
How we detect
- <indentifier> = $#
- $# <op> where <op> is -eq, -ne, -lt, -gt, -le, -ge, =, !=
- case $#
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.