How Do You Use the $# Builtin Linux Variable?

Problem scenario
You want to test the $# built-in Linux variable. Every time you use it, it seems to return "0." How do you see the number of arguments in the most recent command?

Solution
Create a bash script with the following lines "echo... to fi":

echo "This script helps you learn about built-in variables in Linux."
if [ $# -eq 1 ]
   then
       echo "one argument was entered"
   else
       echo $# "arguments were entered."
fi

Run this script like this three times (with passing arguments in the last two):

bash coolscript.sh
bash coolscript.sh foo
bash coolscript.sh foo bar

# The output of the above three commands should demonstrate that $# keeps track of the number of arguments that were entered.

Leave a comment

Your email address will not be published. Required fields are marked *