【问题标题】:Bash script to copy files from cd to directory将文件从 cd 复制到目录的 Bash 脚本
【发布时间】:2013-12-02 22:51:42
【问题描述】:

很遗憾,我没有 bash 脚本知识。我需要一个脚本来读取从 cd 复制的 ONE 文件到目标并重命名它。这是我的代码

#!/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 脚本,或者我可能犯了什么错误。

谢谢

吉姆

【问题讨论】:

    标签: bash if-statement directory copy mount


    【解决方案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/
    

    【讨论】:

    • IF 测试毫无意义,因为它无论如何都会复制匹配的文件。
    • @tvm 目标文件名在每种情况下都不同。
    • 对于 OP:cp $file ... 会更好,以防止多个文件与模式匹配的意外情况。如果您绝对确定只有一个文件会匹配(不多也不少),您可以取消 if 并运行 4 个 cp 命令。
    【解决方案2】:

    另一种选择:

    #!/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”是一个元素,所以没关系)

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多