From 0a226524a66a8c3bcab46a1fd829b8458b2d8613 Mon Sep 17 00:00:00 2001 From: Jeffrey Finkelstein Date: Sat, 19 Mar 2022 12:03:10 -0400 Subject: [PATCH] split: elide all chunks when input file is empty Fix a bug in the behavior of `split -e -n NUM` when the input file is empty. Previously, it would panic due to overflow when subtracting 1 from 0. After this change, it will terminate successfully and produce no output chunks. --- src/uu/split/src/split.rs | 7 +++++++ tests/by-util/test_split.rs | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index 73abc966b..36a95da9a 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -984,6 +984,13 @@ where (num_chunks, chunk_size) }; + // If we would have written zero chunks of output, then terminate + // immediately. This happens on `split -e -n 3 /dev/null`, for + // example. + if num_chunks == 0 { + return Ok(()); + } + let num_chunks: usize = num_chunks .try_into() .map_err(|_| USimpleError::new(1, "Number of chunks too big"))?; diff --git a/tests/by-util/test_split.rs b/tests/by-util/test_split.rs index 642cb7c68..d51aadd3b 100644 --- a/tests/by-util/test_split.rs +++ b/tests/by-util/test_split.rs @@ -571,6 +571,19 @@ fn test_elide_empty_files() { assert!(!at.plus("xad").exists()); } +#[test] +#[cfg(unix)] +fn test_elide_dev_null() { + let (at, mut ucmd) = at_and_ucmd!(); + ucmd.args(&["-e", "-n", "3", "/dev/null"]) + .succeeds() + .no_stdout() + .no_stderr(); + assert!(!at.plus("xaa").exists()); + assert!(!at.plus("xab").exists()); + assert!(!at.plus("xac").exists()); +} + #[test] fn test_lines() { let (at, mut ucmd) = at_and_ucmd!();