From 18f9ca9da4b985d6bcf725bc79f5b887774d71e5 Mon Sep 17 00:00:00 2001 From: Jeffrey Finkelstein Date: Sun, 9 Feb 2025 21:59:04 -0500 Subject: [PATCH] csplit: don't panic on missing suppressed file Avoid a panic that would occur when attempting to remove a file that didn't exist. This would happen when scanning for a regular expression match, advancing by a positive offset, and suppressing empty files. For example, before this commit, echo a | csplit -z - %a%1 would cause a panic. After this commit, the process terminates as expected: without error, without output, and without any files written. Fixes #7251. --- src/uu/csplit/src/csplit.rs | 7 ++++++- tests/by-util/test_csplit.rs | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/uu/csplit/src/csplit.rs b/src/uu/csplit/src/csplit.rs index 501f97582..b0005e75e 100644 --- a/src/uu/csplit/src/csplit.rs +++ b/src/uu/csplit/src/csplit.rs @@ -202,7 +202,12 @@ impl Drop for SplitWriter<'_> { fn drop(&mut self) { if self.options.elide_empty_files && self.size == 0 { let file_name = self.options.split_name.get(self.counter); - remove_file(file_name).expect("Failed to elide split"); + // In the case of `echo a | csplit -z - %a%1`, the file + // `xx00` does not exist because the positive offset + // advanced past the end of the input. Since there is no + // file to remove in that case, `remove_file` would return + // an error, so we just ignore it. + let _ = remove_file(file_name); } } } diff --git a/tests/by-util/test_csplit.rs b/tests/by-util/test_csplit.rs index e062b6d55..7c0036ded 100644 --- a/tests/by-util/test_csplit.rs +++ b/tests/by-util/test_csplit.rs @@ -335,6 +335,16 @@ fn test_skip_to_match_offset() { } } +#[test] +fn test_skip_to_match_offset_suppress_empty() { + let (at, mut ucmd) = at_and_ucmd!(); + ucmd.args(&["-z", "-", "%a%1"]) + .pipe_in("a\n") + .succeeds() + .no_output(); + assert!(!at.file_exists("xx00")); +} + #[test] fn test_skip_to_match_negative_offset() { let (at, mut ucmd) = at_and_ucmd!();