【问题标题】:Writing .sh code编写 .sh 代码
【发布时间】:2013-08-27 00:28:53
【问题描述】:

我从来没有写过 .sh 代码,如果这个问题看起来太明显了,很抱歉:

我有一个在 ubuntu 控制台中运行的可执行文件“executable1”,如下所示: ./executable1 文件名1

这很好用。

考虑到我需要在很多文件上运行此代码(1000 个),我编写了一个 sh 脚本,在其中存储了所有文件名并尝试使 executable1 对它们起作用,如下所示:

#!/bin/bash
filesNames=(fileName1 fileName2 [etc] fileName1000)
numberFiles=1000;
for i in `seq 1 $numberFiles`
do
  ./executable1 ${filesNames[$i]} > results.txt &
done

我在我的 shell 中运行代码(名为 scriptName.sh),如下所示:

bash scriptName.sh 

但是,我收到以下错误:

./executable1: No such file or directory

我不明白,因为当我单独在 shell 中执行 ./executable1 时,它工作得很好......

【问题讨论】:

  • 执行bash scriptname.sh命令时你在哪个目录?要使./executable1 工作,该文件必须存在于当前工作目录中。您可以尝试在脚本中使用绝对路径(例如/some/directory/executable1)以确保找到可执行文件1。
  • 将“相对”路径替换为完整路径,即 /path/to/executable1。您可能会发现其他与 PATH 相关的问题,祝您好运。
  • 可执行文件 1 与 scriptname.sh 位于同一目录中。然而,当我编写完整路径时,它可以工作......谢谢。但是你知道为什么我需要写完整的路径吗?

标签: linux shell executable sh


【解决方案1】:

行后

numberFiles=1000;

写这个

cd /dir/of/the/executable

因此 bash 可以找到可执行文件。

【讨论】:

    【解决方案2】:

    也许更简单的方法是:

    for ii in `ls <path_to_dir_with_1000_files>` ; 
       do
          /dir/of/the/executable/executable1 $ii ;
       done
    

    ...您将这 1000 个列表放入 $ii 数组并使用 for$ii 数组中的每个项目执行 executable1。从您提到 1000 个文件的目录中执行此脚本。

    【讨论】:

      【解决方案3】:

      我会进一步简化为:

      for ii in /path/to/files/*; do
          ./executable1 "$ii" >> results.txt
      done
      

      “>>”很重要,因为您不想覆盖整个 results.txt。另外,不要尝试后台运行任务(“&”),因为您将同时运行一千个进程,这至少会破坏 results.txt 并且可能还会导致您的计算机崩溃。

      但要回答您的问题,executable1 的所有路径(您要运行的脚本、executable1 和文件)都与您运行脚本的位置相关。所以如果你在~/Documents,但是executable1和script在~/bin,文件在~/Documents/Data,你需要运行~/bin/script,脚本需要引用"~/bin /executable1" 和 "~/Documents/Data/*"。在脚本(./foo、../../foo/bar)中编写相对路径是个坏主意,除非您确切知道用​​户在运行脚本时将在哪里。例如,“rename-to-upper-case”脚本可以假设您要对当前目录中的所有文件进行操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-02
        • 2012-07-11
        • 1970-01-01
        相关资源
        最近更新 更多