Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch permission denied errors from the glob operator?

Tags:

linux

bash

perl

The following simple Perl script will list the contents of a directory, with the directory listed as an argument to the script. How, on a Linux system can I capture permission denied errors? Currently if this script is run on a directory that the user does not have read permissions to, nothing happens in the terminal.

#!/bin/env perl

use strict;
use warnings;

sub print_dir {
foreach ( glob "@_/*" )
  {print "$_\n"};
}

print_dir @ARGV
like image 428
GL2014 Avatar asked Jun 20 '13 14:06

GL2014


1 Answers

The glob function does not have much error control, except that $! is set if the last glob fails:

glob "A/*"; # No read permission for A => "Permission denied"
print "Error globbing A: $!\n" if ($!);

If the glob succeeds to find something later, $! will not be set, though. For example glob "*/*" would not report an error even if it couldn't list the contents for a directory.

The bsd_glob function from the standard File::Glob module allows setting a flag to enable reliable error reporting:

use File::Glob qw(bsd_glob);
bsd_glob("*/*", File::Glob::GLOB_ERR);
print "Error globbing: $!\n" if (File::Glob::GLOB_ERROR);
like image 187
Joni Avatar answered Oct 17 '22 03:10

Joni