in reply to chmod for cgi

The specific answer is that the CGI script is likely to be running with reduced privileges ( on a Unix system, this is commonly a user like "nobody" ), and from the command line, the script is running as yourself. Try setting the ownership of the directory so it belongs to the web server process.

The nag-nag answer is, you should think hard about what you're doing. Changing permissions, deleting files, and doing other such things from a CGI script opens you up to a world of possible hacks. Be careful! Consider a cron job instead, or some other indirect method.