简体   繁体   English

Bash脚本CD问题

[英]Bash script cd issues

Hi all I have some problems with my script. 大家好,我的脚本有一些问题。 I've read that changing the current directory from within a script is a bit of an issue. 我已经读过,从脚本中更改当前目录有点问题。 Basically I am looking for a single php file with a project folder and any sub-folders in it. 基本上我正在寻找带有项目文件夹及其中任何子文件夹的单个php文件。 And I want to change the directory to where that folder is and perform a command for it. 我想将目录更改为该文件夹所在的位置并对其执行命令。 So far no luck. 到目前为止没有运气。

function findPHP(){
declare -a FILES
FILES=$(find ./ -name \*.php)
for file in "${FILES[@]}"
do

DIR=`dirname file`
( cd $DIR && doSomethingInThisDir &(...))

done

Any help would be greatly appreciated. 任何帮助将不胜感激。

You are trying to iterate over FILES as an array, but it only has one element. 您尝试将FILES迭代为一个数组,但是它只有一个元素。 In order to make the result of your subshell into an array, you can: 为了使子shell的结果成为数组,您可以:

FILES=($(find ./ -name \*.php))

Note that it splits file names on spaces, so even though you properly quote below, it won't help. 请注意,它会在空格处分割文件名,因此,即使您在下面正确引用,也无济于事。 Alternatively, you could just let it split below (ie using your existing FILES ) and use instead: 或者,您可以让它在下面拆分(即使用现有的FILES )并改为使用:

for file in $FILES

If you are using bash 4 , you may want to have a look at recursive globbing... this would make it a bit easier: 如果您正在使用bash 4 ,则可能需要看一看递归glob ...这将使它变得更容易一些:

for file in **/*.php

Note that you have to have the globstar shell option set, which you could enable with shopt -s globstar . 请注意,必须设置globstar shell选项,可以使用shopt -s globstar启用shopt -s globstar This way is simpler and won't break on whitespace. 这样比较简单,不会在空白处中断。

Also, you probably want $file here: 另外,您可能希望在此处使用$file

DIR=`dirname $file`

Or just use parameter expansion: 或者只是使用参数扩展:

DIR=${file%/*}

There is no reason to use an array, or store the file list in anyway. 无论如何,没有理由使用数组或存储文件列表。 If your find supports -execdir (eg gnufind 4.2.27), then use it. 如果find支持-execdir (例如gnufi​​nd 4.2.27),请使用它。 Otherwise, cd in a subshell as you have done: 否则,像完成操作一样,在子shell中执行cd:

#!/bin/bash
doSomethingInThisDir() ( cd $(dirname $1); ... )
export -f doSomethingInThisDir
find . -type f -exec bash -c 'doSomethingInThisDir {}' \;

I have defined the function using () instead of {} , but that is not necessary in this case. 我已经使用()而不是{}定义了函数,但是在这种情况下这不是必需的。 Normally, using () causes the function to run in a subshell, but that happens here anyway because find runs a separate process for each file. 通常,使用()会使函数在子shell中运行,但是无论如何这里都会发生,因为find为每个文件运行一个单独的进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM