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
Norls
  • 19
  • 1
  • 8
  • 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). – Gordon Davisson Sep 13 '20 at 18:51
  • 1
    This question is a possible duplicate of ["How to pass an array argument to the Bash script"](https://stackoverflow.com/questions/17232526/how-to-pass-an-array-argument-to-the-bash-script) and ["Passing An Array From One Bash Script to Another"](https://stackoverflow.com/questions/16019389/passing-an-array-from-one-bash-script-to-another). – Gordon Davisson Sep 13 '20 at 18:55

1 Answers1

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
Norls
  • 19
  • 1
  • 8