P4R4
P4R4

Reputation: 63

How to create a shell script

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?

Upvotes: 0

Views: 93

Answers (2)

baradm100
baradm100

Reputation: 34

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

Upvotes: 1

Bicky
Bicky

Reputation: 61

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

Upvotes: 0

Related Questions