Blog Archive

Tuesday, March 13, 2018

linux/bash: number of arguments, $#, $@

How do I find the number of arguments passed to a Bash script? - Stack Overflow:



Note:

$#:  number of arguments

$@: all arguments



To clarify: unlike argc in C-like languages, $# will be 0 if there are no arguments passed to the script, 1 if there is one argument, etc. 



#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
    echo "The length of argument '$var' is: ${#var}"
    (( count++ ))
    (( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"
'via Blog this'

No comments:

Post a Comment