View Single Post
  #1   (View Single Post)  
Old 11th June 2021
J65nko J65nko is offline
Administrator
 
Join Date: May 2008
Location: Budel - the Netherlands
Posts: 4,131
Default Shell script arguments or parameters held in '$@' and '$*'

When passing arguments to a shell script it good to know the differences between the behaviour of the '$@' and '$*' special variables. Both of them allow you to retrieve the arguments or parameters passed to your script, but there are subtle differences when you surround them with quotes or not.

A shell script that illustrates these quirks:
Code:
#!/bin/sh
# J65nko - daemonforums.org

echo; echo 'Parameters in "$@" -------'

nr=0
for THIS in "$@" ; do
  nr=$((nr+1))
  echo "Parameter $nr :\t$THIS"
done

echo; echo 'Parameters in $@ -------'

nr=0
for THIS in $@ ; do
  nr=$((nr+1))
  echo "Parameter $nr :\t$THIS"
done

echo; echo 'Parameters in "$*" -------'

nr=0
for THIS in "$*" ; do
  nr=$((nr+1))
  echo "Parameter $nr :\t$THIS"
done

echo; echo 'Parameters in $* -------'

nr=0
for THIS in $* ; do
  nr=$((nr+1))
  echo "Parameter $nr :\t$THIS"
done
Running it with some arguments shows the differences:

Code:
$ ./paramtst.sh "King Alfred the Great" 1 2

Parameters in "$@" -------
Parameter 1 :   King Alfred the Great
Parameter 2 :   1
Parameter 3 :   2

Parameters in $@ -------
Parameter 1 :   King
Parameter 2 :   Alfred
Parameter 3 :   the
Parameter 4 :   Great
Parameter 5 :   1
Parameter 6 :   2

Parameters in "$*" -------
Parameter 1 :   King Alfred the Great 1 2

Parameters in $* -------
Parameter 1 :   King
Parameter 2 :   Alfred
Parameter 3 :   the
Parameter 4 :   Great
Parameter 5 :   1
Parameter 6 :   2
Attached Files
File Type: sh paramtst.sh (515 Bytes, 2643 views)
__________________
You don't need to be a genius to debug a pf.conf firewall ruleset, you just need the guts to run tcpdump
Reply With Quote