1

请注意,我将要发布的这段代码故意不完美,如果目录中有文本文件,但完整代码确实有这样的检查,它将无法工作。但问题在于:

#!/bin/bash 
for d in *; do 
    cd $d 
done 

产生:

./test: line 3: cd: 500: No such file or directory 
./test: line 3: cd: 536: No such file or directory 
./test: line 3: cd: 560: No such file or directory 
./test: line 3: cd: 572: No such file or directory 
./test: line 3: cd: out.txt: No such file or directory 
./test: line 3: cd: prob1: No such file or directory 
./test: line 3: cd: problem2: No such file or directory 
./test: line 3: cd: README: No such file or directory 
./test: line 3: cd: test: No such file or directory 

其中 500、536、560 和 572 是应该能够打开的目录。如果我只做一个 cd 500 那么我可以毫无问题地进入目录。但是当我在 shell 脚本中使用自动化过程时,它就不起作用了。

好吧,在进一步进入程序后,我现在有:


#!/bin/bash
cd "$1"
for d in */; do
    (
         cd "$d"
        for file in $*; do
        (
                bla="$(head -4 $file|tail -1)"
                cd ~cfb43/cs265/a1
                echo $bla > out.txt
                cd
                cd "$1"
                cd "$d"
        )
        done
        cd "$1"
    )
done

我收到:


head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory

我要做的就是进入一个目录并从文件中读取并获取第四行文本并将其打印到我文件夹中的 out.txt 中。我不确定为什么这段代码会卡在 a1 而不是至少 500 或类似的东西。任何进一步的帮助,我会非常感激

4

2 回答 2

5

因为您尝试进入下一个子目录而不离开上一个子目录。你可以做

#!/bin/bash 
for d in */; do 
    cd -- "$d"
    # do some stuff
    cd .. 
done 

或使用子shell

#!/bin/bash 
for d in */; do 
    (
        cd -- "$d"
        # do some stuff
    )
done 
于 2013-10-12T16:25:02.250 回答
1

你确定你在做什么: $* 扩展为参数 $1 $2 .. ${!#}

for file in $*; do

也许你想要: * 扩展为当前目录中的文件

for file in *; do

另一种方法是永远不要更改目录:

for file in */*;do
   head -4 "$file" | tail -1 >> ~cfb43/cs265/a1/out.txt
done

还有另一种方法

head -4 | tail -1

用 sed

sed n '4{p;q}'

用 awk

awk 'NR==4{print;exit}'

用 perl

perl -ne 'if($.==4){print;exit}'
于 2013-10-12T19:36:18.873 回答