0

I use create.sh to create random passwords, where each pw is appened to an array which i echo out and of which i give the expanded version (ie. [@]) to the select script.

In the select script i cant access the array. I echoed its length, which said to be 1. even though 2 elements where in it when i printed seperated by a space. Now i cant access the index of 1 because only index 0 exists which is all elements concatenated by a whitespace.

Thanks in advance. Robert

create.sh

SEQ_LEN=1
MAX_CHAR=25
PASSWORDS=()
COUNTER=0

while getopts "x:l:" OPTION; do
    case $OPTION in
        x )
            SEQ_LEN="$OPTARG"
            ;;
        l )
            MAX_CHAR="$OPTARG"
            ;;
        \? )
            echo "correct usage: create [-x] [SEQ_LEN] [-l] [MAX_CHAR]"
            exit 1
            ;;
    esac
done
shift "$(($OPTIND -1))"

for VAR in $(seq 1 $SEQ_LEN)
do
    PASS=$(openssl rand -base64 48 | cut -c1-$MAX_CHAR)
    PASSWORDS[$COUNTER]="$PASS"
    COUNTER=$(($COUNTER +1))
done
echo "${PASSWORDS[@]}"

select.sh

#!/bin/bash
ARRAY=()
INDEX=0

while getopts "a:i:" OPTION; do
    case $OPTION in
        a )
            ARRAY=$OPTARG
            ;;
        i )
            INDEX=$OPTARG
            ;;
        \? )
            echo "Correct Usage: select [-a] [PASSWORD_ARRAY] [-i] [SELECTED_INDEX]"
            ;;
    esac
done

echo "$ARRAY $INDEX"  # looks identical
echo "${#ARRAY[@]}"  # is 1 - should be 2
2
  • The shell cannot return or pass arrays. echo prints the array's elements with spaces in between, and depending on how you pass that to another script it'll either be a single string with spaces, or multiple separate arguments. But each argument is, by definition, a single string (not an array or anything else complicated). Commented Sep 13, 2020 at 18:51
  • 1
    This question is a possible duplicate of "How to pass an array argument to the Bash script" and "Passing An Array From One Bash Script to Another". Commented Sep 13, 2020 at 18:55

1 Answer 1

1

Thanks for the ans wers and helpful advice. Since bash is so great, it turns out you can just do

ARRAY=( $OPTARG )

and it splits the $OPTARG string by " ", turning it into an "array"

"Obviously" you can just for loop through the string and append to a new variable, that being declared as -a array. source as seen below:

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.