Bash Scripting Stuck on inserting course id's


# Script to insert data from courses.csv and students.csv into students database

PSQL="psql -X --username=freecodecamp --dbname=students --no-align --tuples-only -c"

cat courses_test.csv | while IFS="," read MAJOR COURSE
do
  if [[ $MAJOR != "major" ]]
  then
    # get major_id
    MAJOR_ID=$($PSQL "SELECT major_id FROM majors WHERE major='$MAJOR'")

    # if not found
    if [[ -z $MAJOR_ID ]]
    then
      # insert major
      INSERT_MAJOR_RESULT=$($PSQL "INSERT INTO majors(major) VALUES('$MAJOR')")
      if [[ $INSERT_MAJOR_RESULT == "INSERT 0 1" ]]
      then
        echo Inserted into majors, $MAJOR
      fi

      # get new major_id
      MAJOR_ID=$($PSQL "SELECT major_id FROM majors WHERE major='$MAJOR'")
    fi

    # get course_id
    COURSE_ID=$($PSQL "SELECT course_id FROM courses WHERE course='$COURSE'")

    # if not found
    if [[ -z $COURSE_ID ]]
    then
    # insert course
      INSERT_COURSE_RESULT=$($PSQL "INSERT INTO courses(course) VALUES('$COURSE')")
      if [[ $INSERT_COURSE_RESULT == "INSERT 0 1" ]]
      then
        echo Inserted into courses, $COURSE
      fi

    # get new course_id
    COURSE_ID=$($PSQL "SELECT course_id FROM courses WHERE course='$COURSE'")
    fi
    # insert into majors_courses

  fi
done

Is it simply because you’re getting ahead of the course requirements? I think this step only requires you to move the comments inside the if statement, without actually writing the code yet to do the inserting etc.
I’d remove everything but the comments and see if the step passes then.
(Save the code though, as you can paste it back in in the next step).

doesn’t seem to work

image

Yes, that is the correct code for that step. You’ll see that the PSQL query commands follow in the next steps.
If it’s not working for you though, you could try a soft reset (from the Project Options menu on top-left)? Then try re-entering exactly the same code again…
Alternatively, I had a little issue with a couple of the steps in this project when my code wasn’t accepted but un-indenting allowed it to pass. (I then re-indented and continued without issue).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.