Bash script Create dir and copy specific files

In this tutorial, I will share the bash script Create dir and copy specific files while changing the name in Linux.

My example

path_to_files variable structure folder as below

[root@localhost ~]# tree /home/huupv/
/home/huupv/
├── devopsroles.txt
├── dir
│   └── test.csv
└── huuphan.txt

1 directory, 3 files

dir_names variable will new folder after running bash script as below

[root@localhost ~]# tree folder
folder
├── folder-devopsroles.txt
├── folder-dir
│   └── test.csv
└── folder-huuphan.txt

1 directory, 3 files

Bash script Create dir and copy specific files and change name files/folder.

#!/bin/bash
dir_names=$1
path_to_files='/home/huupv/'

if [ ! -d $path_to_files ]; then
        echo "$path_to_files not found folder";
        exit 1;
fi

if [ -d $dir_names ]; then
        echo "$dir_names is exists";
        exit 1;
fi


echo "Creating $i and copying over files..."
mkdir $dir_names
for i in $(ls $path_to_files); do
    cp -rf ${path_to_files}${i} ${dir_names}/${dir_names}-$i
done

The result after run Bash Script

Bash script Create dir and copy specific files

Thank you for reading the DevopsRoles page!

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.