Search code examples
shellunixshksh

syntax error operand expected (error token is "-") in shell script


Inside the script there is one error i am getting as syntax error operand expected (error token is "-") at line 109

#!/bin/ksh
..............
while read file
do 
    upd_time=$((`date +%s`-`stat -c %Y ${file}`))     #At this line getting error
    file_nm=`basename "${file}"`
..................

In the above live getting error as syntax error operand expected (error token is "-").


Solution

  • You are trying to call stat when file doesn't have a value:

    $ unset file
    $ stat -c %Y $file
    stat: missing operand
    Try 'stat --help' for more information.
    

    If you correctly quote $file, you'll get a slightly better error message:

    $ stat -c %Y "$file"
    stat: cannot stat '': No such file or directory
    

    If you aren't positive about the contents of your input file, try verifying that $file actually contains an existing file before calling stat:

    while IFS= read -r file
    do 
        [ -e "$file" ] || continue
    
        upd_time=$(( $(date +%s) - $(stat -c %Y "$file") ))
        file_nm=$(basename "$file")
        ...
    done