2

I need a script to make a screenshot every x seconds. In the code I'm using touch for simplicity.

When I run the code the first touch(screenshot 1) is run and a file is created. But after waiting 5 seconds it echo for screenshot 2 but touch isn't run. Because no file is created. I have no idea why this would be te case.

#!/usr/bin/env bash
file=$(date +%Y-%m-%d.%H:%M:%S)    
x=1    
while true
do    
  echo "screenshot $x"    
  touch $file.jpg    
  sleep 1      
  x=$[$x+1]    
done
2
  • 1
    Won't this just create the same file over and over and over and over again? No matter how many times it loops it's still just going to create the same file... Commented Jul 2, 2019 at 19:44
  • This runs just fine for me. Are you 100% sure this is exactly the code you're running? Commented Jul 2, 2019 at 20:25

1 Answer 1

5

You should re-assign ${file} every time the loop runs! You're assigning it outside the loop, so you're touching the same filename every time!

x=1

while true; do
  # Assign a new name (with a new timestamp) to $file, and a file
  # with a new name will be created!
  file=$(date +%Y-%m-%d.%H:%M:%S)

  echo "screenshot $x"

  touch $file.jpg

  sleep 1

  x=$(( x + 1 ))

done

Note: Your touch command WAS working, it was just applying the same filename. Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This works. Very logical if you think about it.
No problem bigyu!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.