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

Time:12-23

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 "-").

CodePudding user response:

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

CodePudding user response:

I have reproduced your error:

tmp.txt:

/bin/sh

/bin/bash

test.sh:

while read file; do
  upd_time=$((`date  %s`-`stat -c %Y ${file}`))
  echo $upd_time
done < tmp.txt

output:

44421445
stat: missing operand
Try 'stat --help' for more information.
-bash: 1671714632-: syntax error: operand expected (error token is "-")

You have a blank line in your input file.

  • Related