Computing.Net > Forums > Programming > BASH: Positional parameters

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

BASH: Positional parameters

Reply to Message Icon

Name: Six
Date: July 31, 2003 at 14:34:43 Pacific
OS: Gentoo
CPU/Ram: 1.4/256
Comment:

I've gotten into Bash scripting and wrote a few scripts.
The only thing I can't seem to grasp is passing command line arguments to the script, like ./scriptname.sh -r

if someone could point me to a good doc on this I'd appreciate it. I read the Advanced Scripting Guide and a lot of the small bash programming howto both on tldp.org, both touch on it very lightly.



Sponsored Link
Ads by Google

Response Number 1
Name: Don Arnett
Date: August 1, 2003 at 07:05:06 Pacific
Reply:

In the simplest sense, getting the args is very easy. In your code, you use the variables $0, $1, $2 ...

$0 is always the script name and $1, $2 ... are the first, second, etc space separated arguments. I usually copy them into meaningful named variables:

> MyCleanupScript /data/logs .log

DirName=$1
Extension=$2


There is also a 'shift' command that you can use in the shell script so that you can process the args with a loop:

ArgCount=$#
CurrentArg=$1
shift

while [ $ArgCount -ge 0 ]
do

...

CurrentArg=$1
decrement CurrentArg count - I don't remember the syntax
shift

done


The disadvantage of the above two methods is that the args have to be in the order expected by the code.

To get around that, you use the shell script command 'getopts'. With 'getopts' you can define that you expect a -r arg with one option and -s with no options, and the arguments don't have to be in a specified order, so the same code can handle:

MyScript -d /data/logs -e .logs

and

MyScript -e.logs -d /data/logs

You can read about getopts in 'man bash' or maybe you can find more by doing a google search.


0
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: BASH: Positional parameters

passing vars into bat files www.computing.net/answers/programming/passing-vars-into-bat-files/10554.html

Numbers and basic math in BATCH www.computing.net/answers/programming/numbers-and-basic-math-in-batch/20285.html

How do you use time in bash? www.computing.net/answers/programming/how-do-you-use-time-in-bash/2429.html