Bash 디렉토리 일괄 처리

Linux command line provides powerful tools for working with directories and files. One of the most commonly used scripting languages in Linux is Bash. In this blog post, we will explore how to perform batch processing on directories using Bash scripting.

Batch processing involves executing the same set of commands on multiple directories or files at once. This can save you a lot of time and effort, especially when dealing with large sets of data. Let’s dive into some practical examples.

1. Looping over Directories

To process multiple directories, we can use a for loop in Bash. The loop will iterate over each directory and perform a set of actions.

#!/bin/bash

for dir in /path/to/directory/*; do
  if [[ -d "$dir" ]]; then
    # Process the current directory
    echo "Processing directory: $dir"
    # Add your commands here
  fi
done

In the above example, we use a wildcard (*) to match all the directories within a specific path. The if statement checks if the current item in the loop is a directory using the -d flag. If it is, the subsequent commands will be executed inside the loop.

2. Executing Commands on Directories

Once inside the loop, you can perform various operations on the directories. Here are a few examples:

a. Changing Directory

To navigate into each directory, you can use the cd command.

cd "$dir"

b. Listing Files

To list the files within each directory, you can use the ls command.

ls

c. Copying Files

To copy files from each directory to a specific location, you can use the cp command.

cp file.txt /path/to/destination/

d. Renaming Files

To rename files within each directory, you can use the mv command.

mv oldfile.txt newfile.txt

These are just a few examples of the commands you can use within the loop. The possibilities are endless, depending on your specific requirements.

3. Putting it All Together

Let’s put everything together in a script that demonstrates batch processing on directories. Create a new file called process_directories.sh and add the following code:

#!/bin/bash

for dir in /path/to/directory/*; do
  if [[ -d "$dir" ]]; then
    echo "Processing directory: $dir"
    cd "$dir"
    ls
    # Add your additional commands here
    cd ..
  fi
done

Make sure to replace /path/to/directory/ with the actual path to the directory you want to process. You can then execute the script by running ./process_directories.sh in the terminal.

Conclusion

Bash scripting provides a powerful way to perform batch processing on directories in Linux. By utilizing loops and a set of commands, you can automate repetitive tasks and save time. Experiment with different commands and customize the script according to your needs. Happy coding!