如何在所有目录中的特定文件中循环shell脚本?

时间:2014-09-24 00:20:04

标签: linux bash shell sed sh

Shell Scripting sed Errors:

无法查看/home/xx/htdocs/*/modules/forms/int.php

/ bin / rm:无法删除`/home/xx/htdocs/tmp.26758':没有这样的文件或目录

我的shell脚本出错了。我不确定这个for循环是否会起作用,它旨在爬上一个PHP文件的大目录树,并在每个int.php文件中添加一些函数并进行一些验证。不要问我为什么这不是集中/ OO但是它不是。我尽可能地从这里复制了脚本:http://www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/

#!/bin/bash
OLD="public function displayFunction(\$int)\n{"
NEW="public function displayFunction(\$int)\n{if(empty(\$int) || !is_numeric(\$int)){return '<p>Invalid ID.</p>';}"
DPATH="/home/xx/htdocs/*/modules/forms/int.php"
BPATH="/home/xx/htdocs/BAK/"
TFILE="/home/xx/htdocs/tmp.$$"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do 
 if [ -f $f -a -r $f ]; then
   /bin/cp -f $f $BPATH
   sed "s/$OLD/$NEW/g" "$f" > $TFILE && mv $TFILE "$f"
 else
  echo "Error: Cannot view  ${f}"
 fi
done
/bin/rm $TFILE

这样的通配符甚至可以工作吗?我可以在这样的树上检查每个子目录吗?我是否需要对数组进行预编码并对其进行循环?我该怎么做呢?

另外,PHP代码中的$会破坏脚本吗?

我非常困惑。

1 个答案:

答案 0 :(得分:1)

代码中的问题

  • 您无法使用sed以这种方式替换多行。
  • 您在/ sed命令中使用的OLD中使用s///。这不会起作用
  • [ ! -d $BPATH ] && mkdir -p $BPATH || :太可怕了。使用mkdir -p "$bpath" 2>/dev/null
  • 是的,像这样的通配符可以正常工作但只是因为你的字符串没有空格
  • Doube引用您的变量,或者您的代码将非常危险
  • 单引号字符串或您无法理解您正在逃避的内容
  • 不要使用大写变量名称,您可能会意外地替换bash内部变量
  • 不要使用不存在的文件
  • 您的备份将被覆盖,因为所有文件都被命名为int.php

假设您使用的是GNU sed,我并不习惯其他sed风格。 如果你没有使用GNU sed,用换行符替换\n(在字符串内)应该工作。

固定代码

#!/usr/bin/env bash
old='public function displayFunction(\$int)\n{'
old=${old//,/\\,} # escaping eventual commas
# the \$ is for escaping the sed-special meaning of $ in the search field
new='public function displayFunction($int)\n{if(empty($int) || !is_numeric($int)){return "<p>Invalid ID.</p>";}\n'
new=${new//,/\\,} # escaping eventual commas
dpath='/home/xx/htdocs/*/modules/forms/int.php'
for f in $dpath; do 
    [ -r "$f" ]; then
        sed -i.bak ':a;N;$!ba;'"s,$old,$new,g" "$f"
    else
       echo "Error: Cannot view  $f" >&2
    fi
done

链接