gr0gu3
gr0gu3

Reputation: 815

Reading a file and passing parameters to other shell scripts line by line

So, I am trying to automatize the creation of a user using bash script. I have the script below:

#!/bin/bash

cd /tmp/new/

cat autoid`date +%Y%m%d`.csv | grep "THING" | grep "4B"
while read -r line;
        do
                name=$(awk -F';' '{print $10}' | awk -F' ' '{print $1}')
                surname=$(awk -F';' '{print $10}'|awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}')
                userid=$(awk -F';' '{print $8}')
                bash new_user.sh $userid $name $surname
                sleep 1
                bash basic_access.sh C $userid
                sleep 1
        done

The thing is I'm a bit confused here. I'm testing the command using echo in the place of calling the other bash scripts and it isn't returning me anything but the output of the "cat autoiddate +%Y%m%d.csv | grep "THING" | grep "4B"" line. Tried to pipeline the end of this line to while loop but it isn't working anyway.

What am I doing wrong here?

Upvotes: 0

Views: 101

Answers (1)

chepner
chepner

Reputation: 531165

You need to pipe the output to the while loop. The variable line should be piped separately to each awk process (to fix your immediate problem; keep reading for a better solution):

#!/bin/bash

cd /tmp/new/

cat autoid`date +%Y%m%d`.csv | grep "THING" | grep "4B" |
  while read -r line;
        do
                name=$(echo "$line" | awk -F';' '{print $10}' | awk -F' ' '{print $1}')
                surname=$(echo "$line" | awk -F';' '{print $10}'|awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}')
                userid=$(echo "$line" | awk -F';' '{print $8}')
                bash new_user.sh $userid $name $surname
                sleep 1
                bash basic_access.sh C $userid
                sleep 1
        done

However, repeatedly calling awk to get a single field is inefficient. Let read do the splitting. (Included are other miscellaneous fixes and improvements.)

grep "THING" "autoid$(date +%Y%m%d).csv" | grep "4B" | 
  while IFS=";" read -ra fields; do 
    read name surname <<< "${fields[9]}"
    userid=${fields[7]}
    bash new_user.sh "$userid" "$name" "$surname"
    sleep 1
    bash basic_access.sh C "$userid"
    sleep 1
 done

Upvotes: 2

Related Questions