diff --git a/src/uu/basename/src/basename.rs b/src/uu/basename/src/basename.rs index 242a6a6e9a5..ae3e5de4716 100644 --- a/src/uu/basename/src/basename.rs +++ b/src/uu/basename/src/basename.rs @@ -31,6 +31,23 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let args = args .collect_str(InvalidEncodingHandling::ConvertLossy) .accept_any(); + + // Since options have to go before names, + // if the first argument is not an option, then there is no option, + // and that implies there is exactly one name (no option => no -a option), + // so simple format is used + if args.len() > 1 && !args[1].starts_with('-') { + if args.len() > 3 { + return Err(UUsageError::new( + 1, + format!("extra operand {}", args[3].to_string().quote()), + )); + } + let suffix = if args.len() > 2 { args[2].as_ref() } else { "" }; + println!("{}", basename(&args[1], suffix)); + return Ok(()); + } + // // Argument parsing // diff --git a/tests/by-util/test_basename.rs b/tests/by-util/test_basename.rs index 0c7249b3250..0e8d65657bf 100644 --- a/tests/by-util/test_basename.rs +++ b/tests/by-util/test_basename.rs @@ -174,3 +174,21 @@ fn test_triple_slash() { let expected = if cfg!(windows) { "\\\n" } else { "/\n" }; new_ucmd!().arg("///").succeeds().stdout_is(expected); } + +#[test] +fn test_simple_format() { + new_ucmd!().args(&["a-a", "-a"]).succeeds().stdout_is("a\n"); + new_ucmd!() + .args(&["a--help", "--help"]) + .succeeds() + .stdout_is("a\n"); + new_ucmd!().args(&["a-h", "-h"]).succeeds().stdout_is("a\n"); + new_ucmd!().args(&["f.s", ".s"]).succeeds().stdout_is("f\n"); + new_ucmd!().args(&["a-s", "-s"]).succeeds().stdout_is("a\n"); + new_ucmd!().args(&["a-z", "-z"]).succeeds().stdout_is("a\n"); + new_ucmd!() + .args(&["a", "b", "c"]) + .fails() + .code_is(1) + .stderr_contains("extra operand 'c'"); +}