Bash Commands to Manage Directories and Files

Last Updated on :March 24, 2024

Understanding file and directory operations in Bash is essential for system administrator, developer or Software Tester. In this guide we’ll explore the fundamental commands and techniques to manipulate files and directories efficiently.

1. Navigating Directories:

The cd command stands for “change directory.” It’s used to navigate between directories within the file system. For example:

cd /path/directory

If you want to move up one directory, you can use cd …

cd ..

The pwd command helps you verify your current working directory.

pwd

2. Listing Contents:

Use ls command to list files and directories in the current directory or in a specified directory.

  • -l for detailed information.
  • -a to show hidden files.
  • -h for human-readable file sizes.
  • -t to sorts files by modification time

Example: ls -la will provide a detailed listing of all files and directories in the current directory, including hidden files and directories

ls -la

3. Creating Files and Directories:

To create an empty file, use touch:

touch filename.txt

To create a directory , use mkdir

mkdir new_directory

4. Copying and Moving:

To copy files, use cp:

cp source_file destination

For copying directories, add the -r (or -R) option:

 cp -r source_directory destination_directory 

To move (or rename) files or directories, use mv:

 mv old_name new_name 

5. Removing Files and Directories:

Remove a file with rm:

 rm filename.txt 

Remove a directory and its contents with the -r option:

 rm -r directory_name 

Note: Be cautious when using rm to avoid accidental deletions.

6. Searching for Files:

The find command helps locate files based on various criteria. For instance, to find all text files in a directory:

 find /path/to/search -name "*.txt" 

7. Changing Permissions:

Use chmod to change file permissions. For example, to give read and write permissions to the owner:


chmod u+rw filename.txt

8. Combining Commands with Pipes:

Bash allows you to chain commands using pipes (|). For instance, to list the 10 largest files in a directory:


ls -l | sort -k 5 -rn | head -n 10

9. Wildcard Expansion:

Bash supports wildcard characters for pattern matching. For example, to delete all .log files in a directory:


rm *.log

10. Handling Compressed Files:

To extract a compressed file, use tar:


tar -zxvf filename.tar.gz

To create a compressed file, use:


tar -czvf archive.tar.gz directory

This guide provides a solid foundation for efficiently navigating, manipulating, and managing files and directories using Bash commands

You may also like...

Leave a Reply

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