0
点赞
收藏
分享

微信扫一扫

使用纯 Java 编写 Shebang 脚本

minute_5 2024-11-18 阅读 22


可以像编写 bash 脚本一样轻松地用 Java 编写 CLI 脚本,并直接从 shell 运行它?

这通常被称为 shebang 脚本,尽管我们大多熟悉用 bash 编写它们。Bash 脚本很棒,但对于不熟悉语法的开发人员来说,它们可能晦涩难懂。作为 Java 开发人员,您可能更喜欢以 Java 方式完成工作。好吧,从 Java 11 开始,您就可以这样做!

我假设你的机器上已经安装了 Java。要确认,请打开终端并运行:

java --version

你应该看到类似这样的内容:

java --version
java 21.0.1 2023-10-17 LTS
Java(TM) SE Runtime Environment (build 21.0.1+12-LTS-29)
Java HotSpot(TM) 64-Bit Server VM (build 21.0.1+12-LTS-29, mixed mode, sharing)

如果你没有看到类似的输出,则表示 Java 未安装。很抱歉让你不爽,但你现在需要安装它!最简单的方法是通过SDKMan

在我之前的一篇文章中,我解释了如何使用PicoCLI构建 CLI 应用程序。如果您有兴趣,请随时查看。但在本文中,我们将保持简单,使用纯 Java 而不使用任何外部库。

入门

首先,创建一个名为hello.java

touch hello.java

然后,将以下代码粘贴到文件中:

#!/usr/bin/java --source 21

import java.time.LocalDate;
import java.util.Random;
import java.util.Scanner;

public class HelloCLI {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        System.out.println("Welcome to the Java CLI. Type 'help' for a list of commands or 'exit' to quit.");

        while (true) {
            System.out.print("Command> ");
            String command = scanner.nextLine().trim().toLowerCase();

            switch (command) {
                case "greet" -> System.out.println("Hello, Java enthusiast!");
                case "date" -> System.out.println("Today's date: " + LocalDate.now());
                case "time" -> System.out.println("Current time: " + java.time.LocalTime.now());
                case "random" -> System.out.println("Random number (1-100): " + (random.nextInt(100) + 1));
                case "add" -> {
                    System.out.print("Enter first number: ");
                    double num1 = scanner.nextDouble();
                    System.out.print("Enter second number: ");
                    double num2 = scanner.nextDouble();
                    scanner.nextLine(); // Consume the newline
                    System.out.println("Result: " + (num1 + num2));
                }
                case "multiply" -> {
                    System.out.print("Enter first number: ");
                    double num1 = scanner.nextDouble();
                    System.out.print("Enter second number: ");
                    double num2 = scanner.nextDouble();
                    scanner.nextLine(); // Consume the newline
                    System.out.println("Result: " + (num1 * num2));
                }
                case "help" -> {
                    System.out.println("""
                        Available commands:
                        - greet: Prints a friendly greeting.
                        - date: Displays today's date.
                        - time: Displays the current time.
                        - random: Generates a random number between 1 and 100.
                        - add: Adds two numbers.
                        - multiply: Multiplies two numbers.
                        - help: Shows this help message.
                        - exit: Exits the program.
                        """);
                }
                case "exit" -> {
                    System.out.println("Exiting... Goodbye!");
                    return; // Terminate the program
                }
                default -> System.out.println("Unknown command: " + command + ". Type 'help' for a list of commands.");
            }
        }
    }
}

关键点:Shebang Line

注意第一行:#!/usr/bin/java --source 21。这是文件的关键部分,指示 shell 使用 Java 21 以源形式运行脚本。

.java 如果需要, 您可以删除 扩展名;这也没问题。只需保留名为的文件即可hello。要重命名文件,请使用以下命令:

mv hello.java hello

使其可执行

现在,要使该脚本可执行,请运行以下命令:

chmod +x ./hello

就这样!你现在可以用以下命令运行它:

./hello

运行它时你应该看到以下内容:

./hello
Welcome to the Java CLI. Type 'help' for a list of commands or 'exit' to quit.
Command> help
Available commands:
- greet: Prints a friendly greeting.
- date: Displays today's date.
- time: Displays the current time.
- random: Generates a random number between 1 and 100.
- add: Adds two numbers.
- multiply: Multiplies two numbers.
- help: Shows this help message.
- exit: Exits the program.

Command> greet
Hello, Java enthusiast!
Command> date
Today's date: 2024-10-27
Command> random
Random number (1-100): 99
Command> add
Enter first number: 5
Enter second number: 39999
Result: 40004.0
Command> exit
Exiting... Goodbye!

附加提示:可从任意位置运行

如果您想在机器的任何位置运行此脚本,只需将文件移动到以下/usr/local/bin/文件夹:

sudo mv./hello /usr/local/bin/

现在,您只需hello在终端中输入即可从任何目录调用它。


举报

相关推荐

0 条评论