2

I'm new with bash and doing my first steps in it I want to learn How to store argument localy in script for later use and wrote this script

#!/bin/bash

while getopts ":d" opt;do
     case "${opt}" in
         d)
           d =$OPTARG
           echo "-d was triggered ! storing ${d}" >&2
           ;;
     esac
done

this is my output :

$ -d was triggered! storing 

what is my problem? : I don't store the data correctly or I don't print it correctly or both :)

2 Answers 2

2

Keep : after option name in getopts command :

#!/bin/bash

while getopts "d:" opt; do
     case "${opt}" in
         d)
           d="$OPTARG"
           echo "-d was triggered ! storing ${d}" >&2
           ;;
     esac
done

You also need to remove the spaces around = and better to use quotes in assignment.

Now when you run:

./script.sh -d 1234
-d was triggered ! storing 1234
Sign up to request clarification or add additional context in comments.

1 Comment

this is exactly what I was missing !!
2

Remove whitespace before =$OPTARG. Take a look at http://www.shellcheck.net/

1 Comment

thanks ! but @anubhava's answer is closer to solve my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.