0

I created an array that holds a students name and three grade scores:

studentArray=( [0]="John Doe":100:88:90 )

My trouble is when I run the cut command in the shell, like so

cut -d: -f1 /submit/studentGrades

It displays the whole contents of the bash script instead of just the portion I want, which is the name.

#!/bin/bash

studentArray=( [0]="John Doe"

echo "${studentArray[0]}"

exit 0

If I do field 2 instead like so:

cut -d: -f2 /submit/studentGrades

it only displays the first grade which I want, but it still displays the whole contents of the bash script.

What am I doing wrong? This is my first time working with arrays in Bash Scripting.

Thank you for your help in advance!

jshakil
  • 99
  • 1
  • 11
  • Why are you using `cut` on a script file? – Barmar Oct 04 '17 at 23:32
  • We have to create arrays for five students along with the grades. Then we have to extract the name and all three grades of each student to find the average and then display them. – jshakil Oct 04 '17 at 23:38
  • Why are you doing that by cutting instead of accessing the array directly in the script that assigns it? – Barmar Oct 04 '17 at 23:41
  • Use a loop like `for student in "${studentArray[@]}"` – Barmar Oct 04 '17 at 23:42
  • Yeah but using the loop will just print out all of the items in the array, won't it? I'm trying to access each item individually. I'm a bit confused as to what you mean exactly. I apologize for not understanding. – jshakil Oct 04 '17 at 23:45
  • You can use parameter expansion operators to extract parts of the `$student` string. – Barmar Oct 04 '17 at 23:49
  • How do you expect to use `cut` to loop over all the students in the array? – Barmar Oct 04 '17 at 23:50
  • See https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash – Barmar Oct 04 '17 at 23:52
  • Thank you @Barmar, I appreciate your help! I think I might have been reading the question wrong, it says to store them in a separate file in an array... – jshakil Oct 05 '17 at 00:01

1 Answers1

1

I'm not sure why you're trying to use a script file as a data file.

Use grep to select the line you want before cutting:

grep '^studentArray=' /submit/studentGrades | cut -d: -f1
Barmar
  • 741,623
  • 53
  • 500
  • 612