0

ISSUE: I need to place a users cmd-line argument ( in this case a directory path ) into an associative array using declare -a DIR. The directory path will be stored in the array for later use in the script. However, at the moment that when the proper option & arg is provided by the user nothig is stored in the DIR array. The script is executed as such ./selectDir -d <dir_path> [file1] [file2]

DESIRED OUTPUT: I want the user's selected directory choice to be stored in the array "DIR". I would then like to be able to print the contents of the array once i've stored them so that I can verfiy the storage.

CURRENT CODE:

!/bin/bash -x
# 
# Description:
# Usage:
#
# Issue: current problem seems to be with the execution of the scipt
# --syntax ./parseargs -d [$path] [file1] [file2] ... but this is keeps snagging on error
#

totalArgs="$#"

function usageErr()
{
        echo 'usage: baseline.sh [ -d path ] file1 [file2]'
        echo 'creates or compares a baseline from path '
        echo 'default for path is /'
        exit 2

} >&2 #rename the error output file

function parseArgs ()
{
        # need to figure out how to trigger the conditional

        while getopts "c:" MYOPT
        do
                case "${MYOPT}" in
                        d) # provide a custom directory
                                selectPath=YES
                                DIR+=( "$OPTARG" )
                                ;;

                        *) # any other option provided will result in error
                                usageErr
                                ;;
                esac

        done
        shift $((OPTIND-1))

        #no arguments? too many?
        (( $# == 0 || $# > 2 )) && usageErr

        (( ${#DIR[*]} == 0 )) && DIR=( "/" )

}

declare -a DIR
parseArgs # see about passing the cmd args at this point

echo "DIR: ${DIR[*]}"
echo "TEST: $test"
echo "PATH: $selectPath"
dex
  • 11
  • 6
  • Inside the `parseArgs` function, `getopts` operates on the args passed *to that function*, and you don't pass any. Similarly, when you `shift` in that function, it shifts the function's arguments, but leaves the main script's arguments alone. Because of confusions like this, I tend to recommend putting option and argument parsing directly in the main program, not trying to split it into a function. – Gordon Davisson Oct 26 '20 at 07:05
  • # is missing at the beginning (cut&paste pb). getopts should be passed "d:", not "c:". Pass $* to parseArgs() – Rachid K. Oct 26 '20 at 07:24
  • @RachidK. thanks the "$*" seemed to be the key, – dex Oct 30 '20 at 17:41

0 Answers0