简体   繁体   中英

bash script linux - use directory as user input parameter and copy all the subdirectories to /tmp/ folder with the same name as the input directory

I want to create a script called package.sh which should:

  • Use directory as input parameter (can be relative or absolute pathname)
  • Recursively identify all sub directories of the input directory and recreate this structure in /tmp/. For example: for an input parameter /home/eddy a directory /tmp/eddy is created.
  • All the text files and script files below the input directory should be copied to the corresponding directory in /tmp

I am new to bash script so I would like to get some help. Thanks so much

well why not just copy that directory /home/eddy to /tmp ? you can use some --exclude flags if you use rsync for copying in order to filter the files you need.

Something like this then:

#!/bin/bash
cp -r `realpath $1` /tmp

this copies the dir given as the first argument, to /tmp.

But as you say you only want *.txt and *.sh files copied so this should work instead

#!/bin/bash
cp `find $1 -name "*.txt" | xargs realpath` /tmp
cp `find $1 -name "*.sh" | xargs realpath` /tmp

But this doesn't recreate the directory structure like you want so you need cpio for that

#!/bin/bash
find $1 -regextype posix-awk -regex "(.*\.txt|.*\.sh)" | cpio -pdv /tmp

To include the criteria that the .sh files have to have the executable flag set (skip the copy if it is not set) then we have to use two lines:

#!/bin/bash
find $1 -name "*.txt" | cpio -pdv /tmp
find $1 -perm /u=x,g=x,o=x -name "*.sh" | cpio -pdv /tmp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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