0

Lets say that my script name is test.sh. What i want to do is when I give the command

./tool.sh -f <file>

where file is a file of events(ex events.dat) to do something with awk and when i give the command

./tool.sh -f <file> -id

to do something else. How can I achieve that?

Themis
  • 1
  • 2
  • You should parse the arguments and include some conditionals in your script. – William Pursell Dec 20 '18 at 20:15
  • 2
    In your case, `man getopts`. Also, examine `$3` – William Pursell Dec 20 '18 at 20:16
  • Please try to be as explicit about *exactly* how awk factors into where you're having trouble (which is to say, describing exactly where/how you get stuck trying to apply the existing answers to questions about command-line parsing in bash already on the site); that would differentiate this from similar questions already on the site. – Charles Duffy Dec 20 '18 at 20:42

1 Answers1

0

You could so something like this:

while getopts ":f:i:" o; do
    case "${o}" in
    f)
        file=${OPTARG}
        #Do your awk stuff with $file
        ;;
    i)
        id=1 #or whatever value you want, just to know -i option was used
        ;;
    *)
        #Print help if wrong parameter used
        ;;
    esac
done

if [ -z "$file" ]; then
    #If $file was not set, then -f was not used, so print
    # help and exit, as its a mandatory parameter
fi

#Do something with $file
if [ -z "$id" ];then
    #something else
fi
chepner
  • 497,756
  • 71
  • 530
  • 681
alb3rtobr
  • 311
  • 2
  • 8
  • 1
    In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section "Answer Well-Asked Questions", and the bullet therein regarding questions which "...have already been asked and answered many times before". – Charles Duffy Dec 20 '18 at 20:39