Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
目录上的Bash for循环_Bash_Shell_Loops_For Loop_Directory - Fatal编程技术网

目录上的Bash for循环

目录上的Bash for循环,bash,shell,loops,for-loop,directory,Bash,Shell,Loops,For Loop,Directory,我有一个bash脚本,我想在一个目录中运行一个程序,使用另一个目录中的文件作为输入 有几个输入文件,位于几个不同的目录中,每个文件都用作程序一次迭代的输入 这些文件是每个目录中几个文件类型(.foo)中的一个 我的代码是 cd /path/to/data/ for D in *; do # command 1 if [ -d "$D" ] then cd /path/to/data # command 2 for i in

我有一个bash脚本,我想在一个目录中运行一个程序,使用另一个目录中的文件作为输入

有几个输入文件,位于几个不同的目录中,每个文件都用作程序一次迭代的输入

这些文件是每个目录中几个文件类型(.foo)中的一个

我的代码是

cd /path/to/data/
for D in *; do
    # command 1
    if [ -d "$D" ]
    then
        cd /path/to/data
        # command 2
        for i in *.foo
        do
            # command 3
        done
    fi
done
当我运行脚本时,输出如下

# command 1 output
# command 2 output
# command 3 output
# command 2 output
# command 2 output
# command 2 output
# command 2 output
# command 2 output
.
.
.
因此,脚本只执行一次我希望它执行的操作,之后似乎不会在最后的for循环中进行迭代


这是为什么?

我想你在“then”之后有一个打字错误。。。 更合理的做法是:

then
  cd /path/to/data/$D
  # command 2
但正如cdarke所建议的,最好避免在脚本中使用cd。 您可以得到如下相同的结果:

for D in /path/to/data; do
    # command 1
    if [ -d "$D" ]
    then
        # command 2
        for i in /path/to/data/$D/*.foo
        do
            # command 3
        done
    fi
done
或者,您甚至可以使用查找并避免if部分(代码越少,脚本速度越快):


您更改了目录,但没有更改回来?您的代码不清楚,因为您使用了两次
cd/path/to/data/
。通常,请尽量避免在脚本中使用
cd
,否则您会陷入困境。在可能的情况下,构造和使用完整路径名更容易。例如:
用于i in/path/to/data/*.foo
。这些命令的作用是什么?
for D in $(find /path/to/data -maxdepth 1 -type d)
# -type d in find get's only directories
# -maxdepth 1 means current dir. If you remove maxdepth option all subdirs will be found. 
# OR you can increase -maxdepth value to control how deep you want to search inside sub directories.