2015-09-04 62 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