DaemonForums  

Go Back   DaemonForums > Miscellaneous > Guides

Guides All Guides and HOWTO's.

 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
  #1   (View Single Post)  
Old 11th June 2021
J65nko J65nko is offline
Administrator
 
Join Date: May 2008
Location: Budel - the Netherlands
Posts: 3,767
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, 13 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
 

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
[Solved] How to make 2 separate arguments in 1 bash script? guitarscn Programming 1 31st August 2010 09:12 PM
ask for a shell script Simon Programming 5 27th April 2010 01:07 AM
incrementing within a shell script? spiderpig Programming 5 29th September 2008 08:12 PM
Shell Script. bsdnewbie999 Programming 21 15th July 2008 07:54 AM
shell script with input c0mrade Programming 5 13th July 2008 04:33 AM


All times are GMT. The time now is 11:17 AM.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2021, Jelsoft Enterprises Ltd.
Content copyright © 2007-2010, the authors
Daemon image copyright ©1988, Marshall Kirk McKusick