简体   繁体   English

bash如果条件为循环

[英]bash if conditions as loop

Hi I want to create a bash file, where i define multiple files (the number is not set) and the script checks if a md5 hash for each file exist, and creates one if not? 嗨,我想创建一个bash文件,在其中定义多个文件(未设置编号),脚本检查每个文件是否存在md5哈希,如果不存在,则创建一个? I am stuck with the if loop, how can I define a loop with variable length as a if condition? 我被if循环所困扰,如何将一个可变长度的循环定义为if条件?

COMPARE_FILES=("/folder/file1" "/folder2/file2" "file3" ... "/folderN/fileN")

for i in "${COMPARE_FILES[@]}"
do

    base=${i%%.*}                # does not work?
    file=${##*/}                 # works as expected

    if [ ! -f $COMPARE_DIR/compare/$base.md5 ]; then

        rsync $COMPARE_LOC/"$i" $COMPARE_DIR/compare/       #works as expected
        md5sum $COMPARE_LOC/$file > $COMPARE_DIR/$base.md5
        rm $COMPARE_DIR/compare/$file                        #does not work

    fi
done

I am not able to extract the filename and the base name from the array in the loop, can someone help me perhaps? 我无法从循环中的数组中提取文件名和基本名称,也许有人可以帮助我吗?

To get the basename from a filepath, use basename : 要从文件路径获取基本名,请使用basename

$ i="/file/path/filename.ext"
$ base=$(basename $i)
$ echo $base
filename.ext

Then you can get the filename without extension as you were doing: 然后,您可以像以前一样获取不带扩展名的文件名:

$ fnam=${base%.*}
$ echo $fnam
filename

Or the extension: 或扩展名:

$ extn=${base#*.}
$ echo $extn
ext

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

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