0

Good evening all,

As the title says, I am attempting to parse through a csv file of about 400 lines and add each one using the below script. This is part of a homework assignment and I am not sure what exactly I am doing wrong.

#!/bin/bash
while IFS=, read -r userName firstName lastName gender dob language bloodType zodiac constellation planet genre dino;
do
        ldapadd -x -w 1234568 -D cn=admin,dc=SAMPLE,dc=CLASS,dc=SCHOOL,dc=edu
        dn: uid=$userName,ou=people,dc=SAMPLE,dc=CLASS,dc=SCHOOL,dc=edu
        objectClass: person
        objectClass: top
        objectClass: inetorgperson
        uid: $userName
        cn: $firstName $lastName
        sn: $lastName
        description: $dob
        
done < Males.csv

I am unsure what I am doing wrong, as I keep getting the error: "ldapadd: invalid format (line 1) entry: """

Allen
  • 3
  • 1
  • 1
    1. quote your variables. See [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters). 2. In fact, it's probably best to double-quote the entire multi-line string from `dn:` to `$dob`. 3. Does your script really have that one `ldapadd` command across multiple lines **without** backslash-escaping the newlines? or is that just how you edited it for readability here on this site? but note that quoted multi-line strings don't need backslash at EOL. – cas Nov 30 '21 at 04:13
  • @cas I was unaware of 3. That is, I didnt know about backslash-escaping new lines. Thank you. – Allen Nov 30 '21 at 19:45

1 Answers1

4

ldapadd expects dn: ... from standard input. You need a "Here document":

#!/bin/bash
while IFS=, read -r userName firstName lastName gender dob language bloodType zodiac constellation planet genre dino;
do

ldapadd -x -w 1234568 -D cn=admin,dc=SAMPLE,dc=CLASS,dc=SCHOOL,dc=edu <<EOF
dn: uid=$userName,ou=people,dc=SAMPLE,dc=CLASS,dc=SCHOOL,dc=edu
objectClass: person
objectClass: top
objectClass: inetorgperson
uid: $userName
cn: $firstName $lastName
sn: $lastName
description: $dob
EOF
        
done < Males.csv

Do not! use indentation inside here documents.

basin
  • 1,931
  • 4
  • 20
  • 36
  • That worked. Thank you so much for your help. I had suspected EOF was the key, but I was unsure how to use it. – Allen Nov 30 '21 at 19:44
  • +1. BTW, you can use indentation in here docs by using `<<-` instead of just `<<`. From `man bash`: *"If the redirection operator is `<<-`, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion."* – cas Dec 01 '21 at 01:12
  • @cas Yes, but tab was a bad choice because you can't safely paste tabs into interactive shell – basin Dec 01 '21 at 08:15
  • true, but not really relevant in a script. – cas Dec 01 '21 at 11:45