【问题标题】:running shell scripts in different directories在不同目录中运行 shell 脚本
【发布时间】:2011-12-20 08:06:26
【问题描述】:

我有一个名为 tinkering 的目录,其中包含以下子目录:

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 脚本。

【问题讨论】:

  • 我们不知道“无法运行”是什么意思。
  • 绝对。我假设它缺少 shebang 或不可执行,但可能不是这样。
  • 另外一个关于设计的问题:所有这些script.sh 文件都是一样的吗,只是你从哪个目录运行它,还是他们做不同的事情?
  • @ChrisMorgan by design script.sh 做同样的事情,但所有这些脚本都在修补的子目录中我在目录修补,但是当我在 shell 脚本中编写 cd 时,目录不会改变。

标签: bash shell


【解决方案1】:
for subdir in */; do
  cd "$subdir"
  ./script.sh
  cd ..
done

【讨论】:

  • 一个不错的开始,但是添加几个字符可以消除对cd .. 的需要。
  • @IgnacioVazquez-Abrams:你的意思是像(cd "$subdir"; ./script.sh)那样做吗?
  • 是的,将cd $subdir; ./script-part 括在括号中以对其进行子外壳化。无需 cd “摆脱它”。
  • @Roland Illig 是的,你抓住了正确的东西我想知道如何在 shell 脚本中更改目录,这些目录的名称中有空格,而在我的脚本中,cd 命令无法这样做.
【解决方案2】:

就像其他人指出的那样,“无法运行”可能意味着很多事情。例如。如果你收到一条消息说Permission denied,如果你想用./script.sh调用你的脚本,你必须使用chmod a+x script.sh。

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

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

【讨论】:

  • @flesh 不,这与权限无关,父目录中的脚本无法更改 cd 命令提到的目录
【解决方案3】:

脚本必须是可执行的并且有一个shebang。

在开始时打开#!/bin/sh 并在终端chmod +x myscript.sh 中运行(无论您调用什么脚本)。

如果您尝试执行所有子目录,您还可以使用for 循环更有效地执行此操作(我看到 Roland 已经提供了答案,所以我将省略它)。

【讨论】:

  • 除非您自己将脚本传递给解释器,例如bash somescript.sh.
  • 没错,但按照他所说的运行./script.sh,我认为他很可能不是。
【解决方案4】:

我想这可能会奏效。

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

【讨论】:

    猜你喜欢
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多