Lukap
Lukap

Reputation: 31963

shell script with arguments presented

#!/bin/bash
#if present -a flag then print this echo
#echo "A";
#if -b is present then print b
#echo "B"

#and if -c 10 present how can I read this value '10'  ?

above is how I want to look my script

and I want to be able to start it like this

myscript.sh -a -b -c 10

or

myscript.sh

or

myscript.sh -a -c 10

or

myscript.sh -c 10

and so on

Upvotes: 0

Views: 208

Answers (4)

anubhava
anubhava

Reputation: 785531

Use getopts like this:

arg=-1
while getopts "c:ab" optionName; do
   case "$optionName" in
   a) echo "-a is present";;
   b) echo "-b is present";;
   c) arg="$OPTARG"; echo "-c is present [$arg]";;
   esac
done

Upvotes: 1

Daniel  Magnusson
Daniel Magnusson

Reputation: 9674

#!/bin/bash
for var in "$@"
do
    echo "$var"

http://osr600doc.sco.com/en/SHL_automate/_Passing_to_shell_script.html

Upvotes: 0

teGuy
teGuy

Reputation: 215

You may have a look at getopts .

The following example is taken from http://wiki.bash-hackers.org/howto/getopts_tutorial

#!/bin/bash

while getopts ":a" opt; do
  case $opt in
    a)
      echo "-a was triggered!" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

Upvotes: 0

bmargulies
bmargulies

Reputation: 100133

Type 'man getopt' at your shell, and follow the instructions.

Upvotes: 3

Related Questions