Computing.Net > Forums > Unix > HELP!!! Let script accept arguments

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.

HELP!!! Let script accept arguments

Reply to Message Icon

Name: Arne Matthijssen
Date: March 31, 2003 at 23:39:03 Pacific
OS: Sun
CPU/Ram: unknown/unknown
Comment:

Hi all,

I am writing a unix script and am desperately trying to have it accept parameters not using the $1, $2,.. $9 way but by allowing arguments on the command line, e.g. "call_script -name John -age 24"
instead of "call_script John 24"

in bash 2.03...

Can't find out how to do it... but it must be possible...

please help... thanx alot!!!



Sponsored Link
Ads by Google

Response Number 1
Name: David Perry
Date: April 1, 2003 at 04:10:27 Pacific
Reply:

Look at getopt in the bash shell or getopts in ksh.


0

Response Number 2
Name: WilliamRobertson
Date: April 1, 2003 at 04:39:04 Pacific
Reply:

Here is an example from a script I had:

# Use getopts to scan for -e/-w/-p/-f [filename]:
# (':' after option letter indicates arg expected.
# Leading ':' in optstring suppresses default error messages.)
error_level='ERROR' # Default
prompt_for_comments='FALSE' # Default
while getopts ":ewpf:" opt; do
case $opt in
e ) error_level='ERROR' ;;
w ) error_level='WARNING'; message_prefix='Warning: ' ;;
p ) prompt_for_comments='TRUE' ;;
f ) filename=$OPTARG ;;
* ) print -u2 'fcheck: invalid option.'; exit 1 ;;
esac
done
shift $(($OPTIND -1))

print error_level: $error_level
print prompt_for_comments: $prompt_for_comments
print filename: $filename


Note a couple of limitations though:
* You can only parse single-letter flags, e.g. "-a 24", not "-age 24"
* If an invalid option is passed, there is no straightforward way AFAIK to display the offending option, since "$opt" just gives "?".


0

Response Number 3
Name: nails
Date: April 1, 2003 at 06:52:09 Pacific
Reply:

Arne:

Take a look at the my_getopts function at:

http://www.unixreview.com/documents/s=1344/uni1042138723500/

my_getopts will let you do AGE=24.

There's a version for bash as well as ksh.

Regards,


Nails


0

Sponsored Link
Ads by Google
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 Unix Forum Home


Sponsored links

Ads by Google


Results for: HELP!!! Let script accept arguments

help! on shell script www.computing.net/answers/unix/help-on-shell-script/1545.html

need help-unix script www.computing.net/answers/unix/need-helpunix-script/6516.html

addon to a script--help! www.computing.net/answers/unix/addon-to-a-scripthelp/3375.html