2015-09-04 36 views
2

我有一个名称为“S01.result”到“S15.result”等当前目录中的文件夹列表。我试图写一个脚本,将cd放入名称模式为“sXX.result”的每个文件夹中,并在每个子目录中执行一些操作。Bash cd到增量名称的子目录中

这就是我想:

ext = ".result" 
echo -n "Enter the number of your first subject." 
read start 
echo -n "Enter the number of your last subject. " 
read end 

for i in {start..end}; 
do 
    if [[i < 10]]; then 
    name = "s0$i&ext" 
    echo $name 
    else 
    name = "s$i$ext" 
    echo $name 
    fi 

    #src is the path of current directory 
    if [ -d "$src/$name" ]; then 
    cd "$src/$name" 
    #do some other things here 
    fi 
done 

我是否正确串接文件名,我在寻找正确的子目录?有没有更好的方法来做到这一点?

+1

此脚本中有许多错误。通过http://shellcheck.net运行它来捕捉其中的很多。还有一些错别字。 –

回答

1

你说你需要将cd放入与该模式匹配的每个文件夹中,因此我们可以遍历当前目录中的所有文件/文件夹,以找到与所需模式匹配的子目录。

#!/bin/bash 

# Get current working directory 
src=$(pwd) 

# Pattern match as you described 
regex="^s[0-9]{2}\.result$" 

# Everything in current directory 
for dir in "$src"/*; do 

    # If this is a directory that matches the pattern, cd to it 
    # Will early terminate on non-directories 
    if test -d $dir && [[ $dir =~ $regex ]]; then 
     cd "$dir" 
     # Do some other things here 
    fi 
done