0

I am trying to create a shell script to remove certain files from a directory. How would I be able to achieve this?

Can I write the standard commands in a script as follows:

#!/bin/sh

rm -f /directory/of/file/file1.txt
rm -f /directory/of/file/file2.txt
rm -f /directory/of/file/file3.txt
rm -f /directory/of/file/file4.txt

Or is there a specific way to delete files in a shell script. This is my first question here, so please bear with me as I do not know all the rules.

Thanks in advance :)

Edit:

Thanks for all the answers in a short matter of time, I really appreciate it.

Forgot to mention this will executed by root cron (crontab -e) every Tuesday and Friday @ 5PM.

Do I still need to chmod +x the file if root is executing the file?

3
  • Looks fine to me, try it out! Does it work? Commented Oct 9, 2019 at 10:46
  • Since you said these are specific files, you can either do the way you mentioned. Or you can identify patterns. example: rm -f /directory/of/file/*.txt (to delete all the files with txt extension.) Commented Oct 9, 2019 at 10:55
  • Yes all the files are the same extension but there are some which I don't want to delete. Commented Oct 9, 2019 at 11:12

2 Answers 2

1

Your question can split into a few points:

  1. You can use those commands to delete the specific files (if you have the permissions)
  2. Make sure you add running permissions to the shell script file (that is used to perform the rm commands) by using: chmod +x file_name.sh
  3. In order to delete the folder contents and not the folder itself the command should be: rm -r /path/to/dir/*
Sign up to request clarification or add additional context in comments.

2 Comments

Answer is misleading in my opinion, to delete a file, the specific file doesn't need to have execute permission.
Correct, but the question is focus on the shell script file that is performing the rm command, thanks for the input, made the answer more clear.
0

Yes you can. However if you don't have the permission to delete the files then you may get error on the statement. Try to handle that error and you are good to go

1 Comment

If all the files are been in same directory then better way is to change directory to the said directory and then check the existence of the file and if exists then only removed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.