2011-12-20 233 views
0

我有一个名为tinkering目录已以下子目录:运行shell脚本

saraswati\ and\ durga\ pooja 
64\ yogini\ pooja 
52\ guruwar\ ke\ tap\ se\ unemployment\ finish 
bajrang\ bali\ har\ lete\ ain\ devote\ dukh 
bhoot\ bhagane\ ke\ tareke 
bacho\ ko\ gussa\ ane\ ka\ karan 
durga\ pooja 
khatre\ ke\ nishan\ hanth\ mein 
saraswati\ and\ durga\ pooja 
seb\ chadhane\ se\ ma\ hinnamasta 
bhoot\ bhagane\ ke\ tareke 

每个子目录中有一个名为script.sh脚本。

我的终端上写了一个脚本:

cd ~/tinkering/; 
cd saraswati\ and\ durga\ pooja/; 
./script.sh;  
cd ..; 
cd 64\ yogini\ pooja/; 
./script.sh;cd ../; 
cd 52\ guruwar\ ke\ tap\ se\ unemployment\ finish/; 
./script.sh;cd ../; 
cd bajrang\ bali\ har\ lete\ ain\ devote\ dukh/; 
./script.sh;cd ../; 
cd bhoot\ bhagane\ ke\ tareke/; 
./script.sh;cd ..; 
cd bacho\ ko\ gussa\ ane\ ka\ karan/; 
./script.sh;cd ..; 
cd durga\ pooja/;./script.sh; 
cd ..; 
cd khatre\ ke\ nishan\ hanth\ mein/;./script.sh; 
cd ..;cd saraswati\ and\ durga\ pooja/; 
./script.sh;cd ..; 
cd seb\ chadhane\ se\ ma\ hinnamasta/; 
./script.sh;cd ..; 
cd bhoot\ bhagane\ ke\ tareke/; 
./script.sh;cd ..; 

但是这个脚本无法运行。目的不是去到每个子目录,而是输入./script.sh我可以自动化这个过程。我在上面的代码中犯了什么错误?

编辑 请注意,我写了一篇关于终端用分号隔开这些命令,而我在父目录修修补补的所有子目录有不同的脚本,做不同的工作,我想调用的所有shell脚本子目录从终端上的父目录。

+3

我们不知道“无法运行”是什么意思。 – 2011-12-20 08:12:05

+0

绝对如此。我假设它缺少shebang或不可执行,但这可能不是它。 – 2011-12-20 08:17:07

+0

设计上的另一件事:所有这些'script.sh'文件是否都是相同的,这只是你从哪个目录运行它的问题,还是它们做了不同的事情? – 2011-12-20 08:17:45

回答

3
for subdir in */; do 
    cd "$subdir" 
    ./script.sh 
    cd .. 
done 
+1

一个体面的开始,但增加几个字符可以消除'cd ..'的需要。 – 2011-12-20 08:14:52

+1

@ IgnacioVazquez-Abrams:你的意思是把它做成'(cd“$ subdir”; ./script.sh)'? – 2011-12-20 08:21:35

+0

是的,换行'cd $ subdir; ./script'-部分在括号中以便将其覆盖。不需要cd“离开”。 – plundra 2011-12-20 08:21:47

2

像其他人一样指出,“无法运行”可能意味着一些事情。例如。如果您收到消息Permission denied,则必须使用chmod a+x script.sh,前提是您要用./script.sh调用脚本。

如果您能够使用/some path with whitespace/script.sh运行脚本,则可以将其放入~/tinkering/下的shell脚本中。

find -name script.sh -mindepth 2 -maxdepth 2 -exec sh {} \; 
+0

@flesh否它不是关于权限在父目录中的脚本不能改变cd命令 – 2011-12-20 10:31:40

+0

提到的目录谢谢我已经明白了这是一个新的方法+1。 – 2011-12-20 10:39:18

0

该脚本需要是可执行的并且有一个shebang。

#!/bin/sh放置在开始处并在终端chmod +x myscript.sh(适用于您所谓的脚本)运行。

如果您正在尝试执行所有子目录,您可以使用for循环更有效地执行此操作(我知道罗兰为此提供了答案,因此我将省略它)。

+1

除非您自己将脚本传递给解释器,例如'bash somescript.sh'。 – 2011-12-20 08:17:28

+0

确实如此,但是他正在谈论关于运行'。/ script.sh'的问题,我认为他很可能不是。 – 2011-12-20 08:20:52

0

我想这可能工作。

for d in */; do 
cp scr.sh "$d" 
chmod +x scr.sh 
done 

for subdir in */; do 
    cd "$subdir" 
    ./scr.sh 
    cd .. 
done 

for d in */; do rm scr.sh "$d"; done