[prog] bash script

Jacinta Richardson jarich at perltraining.com.au
Sat Jan 22 15:02:07 UTC 2011


Wolf Rising wrote:
> Would anyone happen to see the syntax error in this code snippet?
> 
> #push information to a file for sed to read
> ls -l /$directory > /tmp/file
> 
> #create file variable
> file="/tmp/file"
> 
> case $var in
>      1) echo "These are regular files:"
>         sed -n '/^-/p' $file
>             if [ "sed -n '/^!-/p' $file" ];
>               then
>                 echo "No items found which match your criteria."
>             fi
>         ;;
> 
> 
> 
> It's a little bash script that checks file types by the first character, I
> wanted to add an if clause but I
> seem to have an error [ "sed -n '/^!-/p' $file" ] as it skips over this an
> prints the echo statement
> whether the file type is found or not.

Unfortunately I don't have any experience with sed's regular expressions, nor do 
I quite remember the syntax for case in bash.  I'm wondering if your code is 
happening outside the case statement and that you only think it's happening in 
the right place due to erroneous indentation.

If you're doing this for the sake of playing with sed, and bash, please ignore 
the next section.

I find Perl to be an excellent tool for this kind of problem.  So I'd write:

#!/usr/bin/perl
use strict;
use warnings;
use autodie;

my $directory = "/tmp";

# get filenames from the directory (use glob("$directory/* $directory/.*) to
# include . files.

while(my $file = glob("$directory/*")) {

     # skip over directories and other non-files
     next unless -f $file;

     # open file for reading
     open(my $fh, "<", $file);

     # read in first line from file
     my $firstline = <$fh>;

     # if the firstline starts with a -, print it out
     # else say it didn't match

     if( $firstline =~ /^-/ ) {
         print "$file\n";
     }
     else {
         print "$file does not start with a '-'\n";
     }
}


I'm fairly sure that does the same thing that you want your snippet to.

All the best,

	Jacinta


More information about the Programming mailing list