How to create a shell script

Issue

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?

Solution

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/*

Answered By – baradm100

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published