需要有关cp函数的指导,以排除某些字符串(第一批/ shell脚本)

时间:2019-01-16 19:41:57

标签: bash shell

我直到最近才开始学习bash / shell脚本来自动完成某些任务。我编写了以下“测试”代码,将文件复制到另一个文件夹:

#!/bin/bash

# Set the parameters
now="$(date)"
fileName="$1"
filePath="$2/"
fileCategory="$3"

# Set the destination folder 
DST_DIR="/Volumes/Mac_Storage/Test_Destination/"

# Change to the folder that contains the film
cd "$filePath"

if [ "$fileCategory" = "Test" ]; then

    shopt -s nullglob
    if [[ -n $(echo *.rar) ]]; then
        rarFile=( *.rar )
        /usr/local/bin/unrar e -r "$rarFile" $DST_DIR
        echo "$rarFile processed" >> ~/Documents/Scripts/log.txt
    elif [[ -n $(echo *.txt) ]]; then
        find . -name '*.txt' | cpio -pdm "$DST_DIR"
        echo ".txt files processed $now" >> ~/Documents/Scripts/log.txt
    elif [[ -n $(echo *.tmp) ]]; then
        find . -name '*.tmp' | cpio -pdm "$DST_DIR"
        echo "*.tmp files processed $now " >> ~/Documents/Scripts/log.txt
    else
        terminal-notifier -message "A file hasn't been found in the folder"
    fi
else
    terminal-notifier -message "A fileCategory was not defined"
fi

现在这段代码只是我扔在一起的,因此,如果可以更好地编写它,那么请指导我,我是否最好将重复的脚本移至另一个.sh(也尝试学习最佳实践),谢谢。

最终,我想将其扩展为包括其他类别,但现在我想要此脚本执行的操作只是

  1. 转到已传递给脚本的目录
  2. 检查文件夹中的文件类型
  3. 将所有这些类型的文件复制到另一个文件夹(当前为测试文件夹),或将unrar复制到测试文件夹
  4. 写入已完成的日志文件(此刻仍在玩此游戏)

现在,在其中包含“ .txt”或“ .tmp”文件的文件夹中,有许多相同的文件类型,其中包含单词“ info”或“ test”。所以现在我的问题

  1. 我可以调整复制所有文件的行,以排除文件名中带有单词“ info”或“ test”的所有文件吗?另外,我将如何编写它以仅排除一个“ info”文件。

如果正在改变代码编写方式,我目前正在Mac上编写此代码。

1 个答案:

答案 0 :(得分:-1)

我只能想象这很可能引起的恐怖尖叫。我为成为异端而感到自豪。 ;)

第一个文件:-

# print.ed

1p
q

第二个文件:-

# pop.ed

1d
wq

第三文件:-

#!/bin/sh -x
#myscript.sh

init () {
find *.txt > stack
mkdir ./mydir
}

next () {
[ -s stack ] && main
}

main () {
filename=$(ed -s stack < print.ed)
[ $(echo ${filename} | sed -n "/foo/p") ] && \
cp -v ${filename} ./mydir
ed -s stack < pop.ed
next
}

init
next