Bash脚本将文件从cd复制到目录

时间:2013-11-19 11:43:48

标签: bash if-statement directory copy mount

我没有幸运的bash脚本知识。我需要一个脚本,将cd从CD拷贝到目的地并将其重命名。这是我的代码

#!/bin/bash

mount /dev/cd0 /mnt/

for file in /mnt/*
do
if($file == SO_CV*)
    cp SO_CV* /usr/castle/np_new/CVFULLPC.BIN
else if($file == SO_PC*)
    cp SO_PC* /usr/castle/np_new/PCMAP.BIN
else if($file == MS_PC*)
    cp MS_PC* /usr/castle/np_new/FULLPC.BIN
else if($file == MS_MC*)
        cp MS_MC* /usr/castle/np_new/MBFULLPC.BIN
done

umount /mnt/

有人可以告诉我这是否是有效的bash脚本,或者我可能犯了什么错误。

由于

吉姆

2 个答案:

答案 0 :(得分:1)

语法问题。试试这段代码:

#!/bin/bash

mount /dev/cd0 /mnt/

for file in /mnt/*; do
   if [[ "$file" == SO_CV* ]]; then
      cp SO_CV* /usr/castle/np_new/CVFULLPC.BIN
   elif [[ "$file" == SO_PC* ]]; then
      cp SO_PC* /usr/castle/np_new/PCMAP.BIN
   elif [[ "$file" == MS_PC* ]]; then
      cp MS_PC* /usr/castle/np_new/FULLPC.BIN
   elif [[ "$file" == MS_MC* ]]; then
      cp MS_MC* /usr/castle/np_new/MBFULLPC.BIN
   fi
done

umount /mnt/

答案 1 :(得分:0)

替代方案:

#!/bin/bash

error_in_cp () {
   { printf "An ERROR occured while trying to copy: '\s' to its dest file.\n" "$@"
     printf "Maybe there were more than 1 file ? or you didn't have the rights necessary to write the destination?"
     printf "Exiting..."
   } >&2  #to have it on STDERR
   exit 1
}    

mount /dev/cd0 /mnt/ &&
for file in /mnt/*; do
   case "$file" in
     SO_CV*) cp -p SO_CV* /usr/castle/np_new/CVFULLPC.BIN || error_in_cp "$file" ;;
     SO_PC*) cp -p SO_PC* /usr/castle/np_new/PCMAP.BIN    || error_in_cp "$file" ;;
     MS_PC*) cp -p MS_PC* /usr/castle/np_new/FULLPC.BIN   || error_in_cp "$file" ;;
     MS_MC*) cp -p MS_MC* /usr/castle/np_new/MBFULLPC.BIN || error_in_cp "$file" ;;
     *)      echo "oops, forgot to handle that case: '$file' . ABORTING. "
             exit 1
             ;;
   esac
done   # no "&&" here so you always umount /mnt/ even if you aborted the copy or the latest command went wrong
umount /mnt/

注意:我将“cp”更改为“cp -p”以更改权利&时间...如果需要调整。

请注意“&&”在行的末尾是好的 (不需要:

 command && \
     something

如果有超过1个元素,则可能需要在每个部分周围添加{}(此处,“case ... esac”是一个元素,所以没关系)