Skip to content

Commit

Permalink
shar: handle filename with space (#565)
Browse files Browse the repository at this point in the history
* shar: handle filename with space

* shar from GNU sharutils can work with a filename with spaces, but this version can't
* Address this by quoting the filename passed to mkdir and sed
* It's not harmful to quote files which don't have a space

%perl shar '0 1' > new.shar
%sh new.shar
x - 0 1
sed: can't read 1: No such file or directory

* improve quoting of filenames containing quotes

* Introduce special quoting function which determines if a filename needs quotes
* Avoid hanging the shell by using the quoted name in the "echo" command as well as sed + mkdir (found during testing)
* Double quotes allow double quotes to be escaped within, and many other punctuation characters don't need an escape
* Some test files I inspected:
%fgrep sed  *.shar 
1.shar:sed -e 's/^X//' >"\"" <<'FUNKY_STUFF'
2.shar:sed -e 's/^X//' >"''" <<'FUNKY_STUFF'
3.shar:sed -e 's/^X//' >"0 1" <<'FUNKY_STUFF'
4.shar:sed -e 's/^X//' >"*" <<'FUNKY_STUFF'
  • Loading branch information
mknos committed Apr 18, 2024
1 parent d64aeb2 commit 968b09a
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions bin/shar
Expand Up @@ -25,11 +25,6 @@ use constant EX_FAILURE => 1;

my $Program = basename($0);

sub usage {
warn "usage: $Program file...\n";
exit EX_FAILURE;
}

getopts('') or usage();
@ARGV or usage();
binmode STDOUT;
Expand All @@ -41,9 +36,14 @@ print '# --cut here--

my $done = 0;
ARGUMENT: for my $f ( @ARGV ) {
if (length($f) == 0) {
warn "$Program: empty file name\n";
next ARGUMENT;
}
my $quoted = quotefile($f);
if (-d $f) {
print "echo x - $f/\n";
print "mkdir -p $f\n";
print "echo x - $quoted/\n";
print "mkdir -p $quoted\n";
$done++;
next ARGUMENT;
}
Expand All @@ -53,7 +53,7 @@ ARGUMENT: for my $f ( @ARGV ) {
}
binmode FH;

print "echo x - $f\n";
print "echo x - $quoted\n";
if (-B $f) {
my $mode = (stat $f)[2];
$mode = (join '', 0, ($mode&0700)>>6, ($mode&0070)>>3, ($mode&0007));
Expand All @@ -63,11 +63,14 @@ ARGUMENT: for my $f ( @ARGV ) {
print pack 'u', $block while read FH, $block, 45;
print "end\n";
} else {
print "sed -e 's/^X//' >$f <<'FUNKY_STUFF'\n";
print "sed -e 's/^X//' >$quoted <<'FUNKY_STUFF'\n";
print 'X', $_ while ( <FH> );
}
print "FUNKY_STUFF\n";
close(FH);
unless (close FH) {
warn "$Program: can't close '$f': $!\n";
next ARGUMENT;
}
$done++;
}
if ($done == 0) {
Expand All @@ -76,6 +79,20 @@ if ($done == 0) {
}
exit EX_SUCCESS;

sub usage {
warn "usage: $Program file...\n";
exit EX_FAILURE;
}

sub quotefile {
my $name = shift;
if ($name =~ m/[\s\'\"\(\)\[\]\{\}\;\:\*]/) {
$name =~ s/\"/\\\"/g;
$name = "\"$name\"";
}
return $name;
}

__END__
=head1 NAME
Expand Down

0 comments on commit 968b09a

Please sign in to comment.