0

So I wanted to make a script in shell that when executed, either modifies a file or echoes back a message.

Here is what I managed to write:

#!/bin/bash

current=$(date +%s)
last_modified='stat -c "Y" $/home/userr/textfile'

if
[ $((current-last_modified)) -gt 120 ]; then
        touch /home/userr/textfile;
else
        echo "File was modified less than 2 minutes ago";
fi

ShellCheck says everything is okay, but when I try to execute it it says: stat -c "Y" $/home/userr/textfile: syntax error: invalid arithmetic operator (error token is ""Y" $/home/userr/textfile")

Any idea where I do go wrong? Thank you in advance!

2
  • I think you mean "%Y"? Commented Nov 7, 2019 at 21:05
  • Thats exactly where I was wrong. Thank you alot for noticing. :) Commented Nov 8, 2019 at 7:43

1 Answer 1

2

Your immediate problem might be this line:

last_modified='stat -c "Y" $/home/userr/textfile'

There you assign the string stat -C "Y" ... to the variable. What you might want to do instead is assigning the output of a command like stat -c %Y /home/userr/textfile which you could write as follows:

last_modified="$(stat -c %Y /home/userr/textfile)"

I recommend using #!/bin/sh -e for all shell scripts (you do not need bash here :) ) where -e enables fail-fast behaviour such that errors do not go undetected.

3
  • That's exactly where I was wrong. Thank you very much for noticing. But why didn't shellcheck tell me the error? Commented Nov 8, 2019 at 7:44
  • Shellcheck does not detect that error because the other thing is a perfectly valid shell script from a syntactical point of view :) Its static analysis does not detect that at runtime, the variable last_modified will be some text (stat ...) instead of a number as required for the $((current - last_modified)) part. Commented Nov 8, 2019 at 17:07
  • Will have that in mind. Thank you alot. :) Commented Nov 9, 2019 at 9:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.