0

I am creating a shell script that uses flags to pass arguments. But I've tried a lot of what I found online but nothing seems to work and I don't know why. This is my script

#!/bin/bash

while getopts "uri:reg:" flag
do
     case $flag in
         uri)
           echo "Recognized the uri flag"
           ECR_REPO_URI=$OPTARG ;;
         reg)
           echo "Recognized the reg flag"
           AWS_REGION=$OPTARG ;;
     esac
done

echo $ECR_REPO_URI
echo $AWS_REGION



IFS='/' read -ra arr <<< "$ECR_REPO_URI"
REPO_NAME=${arr[1]}

aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $ECR_REPO_URI

IMAGE_TAGS=($(aws ecr list-images --repository-name $REPO_NAME --region $AWS_REGION --output json | jq -r '.imageIds[].imageTag'))

last_tag=${IMAGE_TAGS[-1]}

if [[ $last_tag == v* ]] ;
then
        correct_tag=1
else
        correct_tag=0
fi

create_tag() {
        local tag=$1
        tag=$(echo $tag | cut -c 2-)
        IFS='.' read -ra arr <<< "$tag"
        prim_tag=${arr[0]}
        sec_tag=${arr[1]}
        if [[ $sec_tag < 9 ]]
        then
                new_prim_tag=$prim_tag
                new_sec_tag=$(($sec_tag + 1))
        else
                new_sec_tag=0
                new_prim_tag=$(($prim_tag + 1))
        fi
        echo $new_prim_tag.$new_sec_tag
}

if [[ $correct_tag == 1 ]] ;
then
        tag=$(create_tag $last_tag)
else
        tag="0.0"
fi

echo "v$tag"

I enter this is my terminal. ./tagging.sh -uri test -reg test But when I print my variables with echo it just prints empty lines. All help is greatly appreciated!

LinFelix
  • 1,026
  • 1
  • 13
  • 23
david backx
  • 163
  • 1
  • 9
  • 3
    `man bash` and search for `getopts`. You'll eventually get to the section where it's usage is defined. Note that `optstring contains the option characters to be recognized;` . Characters, not strings. Sorry. I think you have to write your own processing, or learn to work with `-u` instead of `-uri`, etc. Long options usually start w `--` . Not sure what to use for that and my dog needs a walk. Good luck. – shellter Apr 25 '23 at 14:05
  • 3
    [tag:bash] - "For shell scripts with syntax or other errors, please check them at https://shellcheck.net before posting them here.". Also see [using-getopts-to-process-long-and-short-command-line-options](https://stackoverflow.com/questions/402377/using-getopts-to-process-long-and-short-command-line-options) or processing long options and see [correct-bash-and-shell-script-variable-capitalization](https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization) for what's apparently wrong with some of your variable names (which shellcheck wouldn't report) – Ed Morton Apr 25 '23 at 15:22

0 Answers0