简体   繁体   English

如何创建 shell 脚本

[英]How to create a shell script

I am trying to create a shell script to remove certain files from a directory.我正在尝试创建一个 shell 脚本来从目录中删除某些文件。 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.或者是否有特定的方法来删除 shell 脚本中的文件。 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.忘了提这将由 root cron (crontab -e) 每周二和周五 @ 下午 5 点执行。

Do I still need to chmod +x the file if root is executing the file?如果 root 正在执行文件,我还需要 chmod +x 文件吗?

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确保使用以下命令将运行权限添加到 shell 脚本文件(用于执行rm命令): 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/*为了删除文件夹内容而不是文件夹本身,命令应该是: rm -r /path/to/dir/*

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尝试处理该错误,您对 go 很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM