【问题标题】:find out which files exists in shell script [duplicate]找出shell脚本中存在哪些文件[重复]
【发布时间】:2021-06-12 05:58:11
【问题描述】:

我有一个现有的 shell 脚本来检查文件是否存在:

[ -f $FULL_FILE_PATH ] && echo FILE_EXISTS

我从 java 调用这个脚本。但是假设我有 20 个文件,在这种情况下我调用这个脚本 20 次。有没有一种方法可以通过传递文件列表来调用这个脚本一次?这样,我可以跳过这个脚本调用的一些额外重复。

【问题讨论】:

  • 您可以在 Java 代码中检查文件是否存在
  • 您到底想要它做什么?为每个存在的文件打印FILE_EXISTS?如果任何文件存在,则一次,如果没有,则根本不存在?或者如果所有文件都存在则一次,如果不存在则根本不存在?
  • 我想为存在的文件打印$FULL_FILE_PATH。 @约瑟夫
  • Files.exists() 是您应该使用的,而不是从 java 运行 shell 脚本...

标签: bash shell


【解决方案1】:

不确定你想做什么,但你可能有自己的理由。

test.bash

while [ -n "$1" ]; do
    file="$(realpath "$1")"
    if [ -f "$file" ]; then
        echo "File exist: $file"
    fi
    shift
done

在 java 中,您可以将要检查的文件作为参数提供给脚本。

public static void main(String[] args)
{
    BufferedReader in = null;
    OutputStreamWriter out = null;
    try {
        ProcessBuilder pb = new ProcessBuilder("bash").redirectErrorStream(true);
        Process p = pb.start();
        in = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8));
        out = new OutputStreamWriter(p.getOutputStream(), StandardCharsets.UTF_8);
        out.write("test.bash file1 file2 file3 file4\n");
        out.write("exit\n");
        out.flush();
        String str;
        while((str = in.readLine()) != null) {
            System.out.println(str);
        }
        int response = p.waitFor();
            System.out.println("response: " + response);
    } catch(IOException e) {
        e.printStackTrace();
    } finally {
        try { in.close(); } catch(Exception e) {}
        try { out.close(); } catch(Exception e) {}
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-12
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2023-04-05
    • 2018-01-24
    相关资源
    最近更新 更多