Hello stackpeople!
I have 2 things to solve and display the results online in a cgi-file.
A) get all foldernames at a given path
B) determine the age of the index.html inside each folder
the result should look like this:
[Number] [Foldername] [fileage]
This cgi-page runs on a solaris server with installed perl 5.8.4
My solution is a combination of bash and perl. To solve problem A) (the folder names) I have written a bash script:
#!/bin/bash
#
find /test/ -type d | sed -e 's/^.*\///'
This gives me a nice list of all foldernames in /test/
Now the perl code to show this output in a browser:
#Establish a pipeline between the bash and my script.
my $bash_command = '/test./foldernames.bash';
open(my $pipe, '-|', $bash_command) or die "Can't open pipe: $!";
# initialize variables
my $foldername = "";
my $i = 0;
# Process the output from bash command line by line.
while (my $line = <$pipe>)
{
$foldername = $line;
$i = $i+1;
print" <tr><td>$i</td><td>$foldername</td></tr>";
}#end while
This works! I’ll get a nice table with [Number] and [Foldername] ! Now comes the tricky part! In addition, I want the date of an index.html located in each folder. Therefore I have another bash script:
ls -ltr /test/folder1/*.html | tail -1 | awk '{printf"%3s %1s %s\n",$6, $7, $8}`
This gives me the perfect output: Feb 22 10:56 Now I need this information in my table. I have added this line in my perl script within the while loop:
$timestamp = `ls -ltr /test/folder1/*.html | tail -1 | awk '{printf"%3s %1s %s\\n",\$6, \$7, \$8}`;
This works perfect when I add the foldername as a string. As soon as I exchange folder1 with $foldername I’ll get nonsense “ls” information.
Why is that so?
Edit: Now I have used:
use File::stat;
use Time::localtime;
my $timestamp = ctime(stat("/test/folder1")->mtime);
This is way more secure compared to parsing the ls output. But still I have issues with the $foldername. I have used the length function to determine the length of $Foldername.
$foldername has a length of 7, but the string output has only 6 chars: tomato
So I’ve tried Chop/chomp the $foldername with always the same result: 7 chars!
Firstly, don’t parse
lsoutput programmatically. It’s nearly guaranteed to break at some point, and to do so in some spectacular fashion. Parsing the output offindis only marginally safer (directory names on most Unixes can contain newline characters, for example; I don’t see your code dealing well with that possibility).Perl has a
statfunction which will give you the date and time of any file or directory (atime, mtime, or ctime, as available), as well as a bunch of other information. You can then use something likestrftimeto format these timestamps for nicer output.