3

I have a script that will try to extract the file's base name and then I do additional work with it. Only when using this script with a file with this naming convention (including spaces and characters - not really sure what's triggering the error), do I get the basename extra operand error.

The file name: JERASH - XZ 837367432.pdf

Here the script once executed generates error:

filetimestamp=$(date "+%F-%T")
timenow=$(date -u)

    for file in files/input/*
    do

     printf "Break 1 \n" 
     #filename no extension:
     filenamenopath=$(basename $file)
     filenamenoext=${filenamenopath%.pdf}
     printf "Break 2 \n"
     #check if file is pdf

     printf "File Name with No Path:" $filenamenopath
     printf "Break 3 \n"

And here is the error:

Break 1 basename: extra operand ‘XZ’

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
ksa_coder
  • 153

1 Answers1

7

The command basename $file uses an unquoted variable. The value of the variable would be split into separate arguments (and each argument would additionally undergo filename globbing) and given to the basename utility.

This utility expects either one or two arguments. With two arguments it will return the filename without any directory path, and it will additionally trim the second argument off from the end of the name (so that basename path/to/file.txt .txt returns file). You are giving it four arguments, since that's how many words the filename JERASH - XZ 837367432.pdf splits into.

Instead, quote the $file variable expansion:

filenamenoext=$(basename "$file" .pdf)

(note that filenamenopath is not needed unless you need it for something else later)

See also:

Also, when using printf to print variable data, make use of the format string and quote the variable:

printf 'Filename without path: %s\n' "$filenamenopath"
Kusalananda
  • 333,661