MaxG
MaxG

Reputation: 227

Bash script not producing desired result

I am running a cron-ed bash script to extract cache hits and bytes served per IP address. The script (ProxyUsage.bash) has two parts:

  1. (uniqueIP.awk) find unique IPs and create a bash script do add up the hits and bytes
  2. run the hits and bytes per IP

ProxyUsage.bash

#!/usr/bin/env bash
sudo gawk -f /home/maxg/scripts/uniqueIP.awk /var/log/squid3/access.log.1 > /home/maxg/scripts/pxyUsage.bash
source /home/maxg/scripts/pxyUsage.bash

uniqueIP.awk

{
  arrIPs[$3]++;
}

END {

  for (n in arrIPs) {
    m++;                               # count arrIPs elements
    #print "Array elements: " m;
    arrAddr[i++] = n;                  # fill arrAddr with IPs
    #print i " " n;
  }

  asort(arrAddr);                      # sort the array values

  for (i = 1; i <= m; i++) {           # write one command line per IP address
    #printf("#!/usr/bin/env bash\n");
    printf("sudo gawk -f /home/maxg/scripts/proxyUsage.awk -v v_Var=%s /var/log/squid3/access.log.1 >> /home/maxg/scripts/pxyUsage.txt\n", arrAddr[i])
  }
}

pxyUsage.bash

sudo gawk -f /home/maxg/scripts/proxyUsage.awk -v v_Var=192.168.1.13 /var/log/squid3/access.log.1 >> /home/maxg/scripts/pxyUsage.txt
sudo gawk -f /home/maxg/scripts/proxyUsage.awk -v v_Var=192.168.1.14 /var/log/squid3/access.log.1 >> /home/maxg/scripts/pxyUsage.txt
sudo gawk -f /home/maxg/scripts/proxyUsage.awk -v v_Var=192.168.1.22 /var/log/squid3/access.log.1 >> /home/maxg/scripts/pxyUsage.txt

TheProxyUsage.bash script runs as scheduled and creates the pxyUsage.bash script. However the pxyUsage.text file is not amended with the latest values when the script runs. So far I run pxyUsage.bash every day myself, as I cannot figure out, why the result is not written to file.

Both bash scripts are set to execute. Actually the file permissions are below:

-rwxr-xr-x  1 maxg maxg  169 Mar 14 08:40 ProxySummary.bash
-rw-r--r--  1 maxg maxg  910 Mar 15 17:15 proxyUsage.awk
-rwxrwxrwx  1 maxg maxg  399 Mar 17 06:10 pxyUsage.bash
-rw-rw-rw-  1 maxg maxg 2922 Mar 17 07:32 pxyUsage.txt
-rw-r--r--  1 maxg maxg  781 Mar 16 07:35 uniqueIP.awk

Any hints appreciated. Thanks.

Upvotes: 0

Views: 63

Answers (1)

Oldest Software Guy
Oldest Software Guy

Reputation: 741

The sudo(8) command requires a pseudo-tty and you do not have one allocated under cron(8); you do have one allocated when logged in the usual way.

Instead of mucking about with sudo(8), just run the script as the correct user.

If you cannot do that, then in the root crontab, do something like this:

su - username /path/to/mycommand arg1 arg2...

This will work because root can use su(1) without neding a password.

Upvotes: 1

Related Questions