diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index 428d62443..bd651bc57 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -13,10 +13,10 @@ use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write}; use std::num::TryFromIntError; #[cfg(unix)] use std::os::fd::AsFd; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use thiserror::Error; use uucore::display::{Quotable, print_verbatim}; -use uucore::error::{FromIo, UError, UResult}; +use uucore::error::{FromIo, UError, UResult, USimpleError}; use uucore::line_ending::LineEnding; use uucore::translate; use uucore::{format_usage, show}; @@ -510,6 +510,13 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { Ok(()) } else { + if Path::new(file).is_dir() { + show!(USimpleError::new( + 1, + translate!("head-error-reading-file", "name" => file.quote(), "err" => "Is a directory") + )); + continue; + } let mut file_handle = match File::open(file) { Ok(f) => f, Err(err) => { diff --git a/tests/by-util/test_head.rs b/tests/by-util/test_head.rs index e35d347f3..d954aa9d9 100644 --- a/tests/by-util/test_head.rs +++ b/tests/by-util/test_head.rs @@ -911,3 +911,11 @@ fn test_head_non_utf8_paths() { assert!(output.contains("line3")); } // Test that head handles non-UTF-8 file names without crashing + +#[test] +fn test_do_not_attempt_to_read_a_directory() { + new_ucmd!() + .arg(".") + .fails_with_code(1) + .stderr_contains("error reading '.'"); +}