0

i need to create a bash that get input from user and insert them into an array until user enter an specific thing. for example, if i run script:

enter variables: 3 4 7 8 ok  

i get this array: array=( 2 4 7 8 )

or:

enter variables: 15 9 0 24 36 8 1 ok

i get this array: array=( 15 9 0 24 36 8 1 )

how i can achieve this?

1

With newline as the default separator:

read -a array -p "enter variables: "

If you want a different character than newline, e.g. y:

read -a array -d y -p "enter variables: "

You can only use a single character as delimiter with read.

EDIT:

A solution that works with the ok delimiter:

a=
delim="ok"
printf "enter variables: "
while [ "$a" != "${a%$delim}${delim}" ]; do
    read -n1         # read one character
    a="${a}${REPLY}" # append character
done
array=(${a%$delim})  # remove "ok" and convert to array
unset a delim        # cleanup
echo                 # add newline for following output

Note: This version also accepts input of the form 3 4 7 8ok (without the last space character), but line editing with special characters like Del or Backspace doesn't work. They're treated as raw input.

  • i put echo $array in my bash for test and it only returned first value. – BlackCrystal Jun 23 at 4:41
  • 1
    You need to echo "${array[@]}". With $array you get the first value like with ${array[0]}. – Freddy Jun 23 at 4:42
  • 1
    This does not answer the question. The ok does not seem to matter, and it is left in the array. – Kusalananda Jun 23 at 8:12
  • @Kusalananda It does if the newline or the y is the "specific thing" (ok). – Freddy Jun 23 at 14:02
  • @Kusalananda Added a version for the ok delimiter. – Freddy Jun 23 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.