函数与脚本 - Unix Bash 编程
我对编程相当陌生(大约一年 - 使用 java),并且对 bash 非常陌生(大约六周)。我编写了一个小型应用程序,它可以执行一些操作,并且它完全由脚本组成。没有一项功能。我知道我可以拥有一个包含所有功能的文件,但为什么和/或何时应该这样做。
例如,我有一个名为 getID 的脚本,它调用“validateID”脚本来确保 id 有效(正好 3 个数字长,例如 827 395 148),然后检查“ids”文件中的特定 ID,如果验证并找到该 ID,则返回 true。
然后我有另一个名为 getID2 的脚本,它验证 id 并在未找到 id 时返回 true。
我最近发现了 getopt 命令,我可以在其中说 getID -f 如果找到则返回 true,而 getID -n 如果未找到则返回 true。或者我可以编写一个函数 getID(),如果找到则返回 0,如果未找到则返回 1。
我目前正在尝试用更好的逻辑来编写应用程序。我会接受有关程序任何部分的任何建议,但我真的很想知道何时应该使用函数和/或何时应该使用脚本。该计划的具体信息如下。
具体细节- 该应用程序是一个小型报告系统,其中有 ID、姓名和分数的列表。我可以根据某人的 ID 查看、编辑、更新或删除某人。
I am fairly new to programming (about one year - with java) and extremely new to bash (about six weeks). I wrote a small application that does a few things, and it consits of entirely scripts. Not one function. I know I can have one file with all functions but why and/or when should I.
For example I hav a script called getID that calls a "validateID" script to make sure the id is valid (exactly 3 numbers long ex. 827 395 148), then checks an "ids" file for the specific id and returns true if the id is validated and found.
Then I have another script called getID2 that validate the id and returns true if the id is not found.
I recently found the getopt command where I can say getID -f to return true if found and getID -n to return true if not found. Or I can write a function getID() that returns 0 if found and 1 if not found.
I am currently trying to write the application over with better logic. I'll accept any advice for any part of the program, but I would really like to know when should I use functions and/or when should I use scripts. Specifics for the program are below.
Specifics -
The application is a small reporting system where i have a list of ids, names and scores. I can view, edit, update, or delete someone based on their id.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一般规则,您应该只为具有重要独立实用程序的东西创建一个全新的脚本。如果它存在的唯一原因是被主脚本调用,那么它应该是主脚本中的一个函数。
编辑:如果要从多个独立脚本调用特定函数(或函数集),您可以将该函数作为函数放入单独的文件中,并在使用它的各个脚本中获取它。
As a general rule, you should only create a whole new script for something when it has significant standalone utility. If the only reason for its existence is to be called by the main script, it should be a function in the main script.
Edit: If a particular function (or set of functions) is going to be called from multiple standalone scripts, you can put that function as a function into a separate file and source it in the various scripts where it's used.