0

I have an automation script that I'm writing in Bash. I need to execute a perl script from within this and capture/parse one specific part of it's output and use it as a variable in order to complete the bash script's tasks.

For example:

echo "Creating database for "$custname
perl /home/dib/testing/addCustomer.cgi name=$custname prefix=$customerno

The perl script "addCustomer.cgi" will return JSON output of:

Content-Type: application/json; charset=UTF-8

{
   "recordcount" : 1,
   "status" : "OK",
   "statusText" : "Add Customer: 40:Testing",
   "customer" : [
      {
         "address" : "",
         "city" : "",
         "country" : "US",
         "description" : "",
         "email" : "",
         "endDate" : "0000-00-00 00:00:00",
         "frontendurl" : "",
         "phone" : "",
         "prefix" : "testing",
         "startDate" : "0000-00-00 00:00:00",
         "state" : "",
         "customerID" : "40",
         "subscriberName" : "Testing",
         "url" : "",
         "zip" : ""
      }
   ],
   "timestamp" : 1559163419
}

What I need to capture is the customerID number, stick it into a variable, and use it to finish the bash script. Is something like this possible? I always see parsing or passing from bash to perl but not the other way around.

misterjones
  • 41
  • 1
  • 6
  • Can't you modify the Perl script to return just the id instead of the full json? – choroba Jul 10 '19 at 17:12
  • "_modify the Perl script to return just the id_" -- or add to it a command-line option for that – zdim Jul 10 '19 at 17:19
  • @zdim: Yes, that's the best way how to modify it :) – choroba Jul 10 '19 at 17:29
  • @choroba no, I can't modify the perl script. I'm just trying to automate a process that currently requires executing the script, noting the value of customerID, then using that with a different command to complete the task. – misterjones Jul 10 '19 at 18:54
  • 1
    As perl is already installed, you can pipe the output to `perl -MJSON::PP -0777 -ne 's/^.*$//m; print decode_json($_)->{customer}[0]{customerID}'`. – choroba Jul 10 '19 at 19:00

1 Answers1

1

Append this to your Perl command:

| sed 1d | jq -r '.customer[].customerID'

Output:

40

I assume there's one header line.

Cyrus
  • 84,225
  • 14
  • 89
  • 153