In this section, we will cover the essential commands for managing files and directories in Bash. These commands are fundamental for navigating and manipulating the filesystem.
Key Concepts
- File and Directory Creation
- Listing Files and Directories
- Copying and Moving Files
- Removing Files and Directories
- Viewing File Contents
- File and Directory Creation
touch
Command
The touch
command is used to create an empty file or update the timestamp of an existing file.
mkdir
Command
The mkdir
command is used to create a new directory.
Practical Example
# Create a new file named example.txt touch example.txt # Create a new directory named example_dir mkdir example_dir
- Listing Files and Directories
ls
Command
The ls
command lists the contents of a directory.
Common Options for ls
-l
: Long listing format-a
: Include hidden files-h
: Human-readable file sizes
Practical Example
# List all files and directories in long format ls -l # List all files, including hidden ones, in human-readable format ls -lah
- Copying and Moving Files
cp
Command
The cp
command copies files or directories.
mv
Command
The mv
command moves or renames files or directories.
Practical Example
# Copy example.txt to example_copy.txt cp example.txt example_copy.txt # Move example.txt to example_dir/ mv example.txt example_dir/
- Removing Files and Directories
rm
Command
The rm
command removes files or directories.
rmdir
Command
The rmdir
command removes empty directories.
Practical Example
# Remove a file named example.txt rm example.txt # Remove an empty directory named example_dir rmdir example_dir
- Viewing File Contents
cat
Command
The cat
command displays the contents of a file.
less
Command
The less
command allows you to view the contents of a file one page at a time.
Practical Example
# Display the contents of example.txt cat example.txt # View the contents of example.txt one page at a time less example.txt
Exercises
Exercise 1: Create and List Files
- Create a file named
testfile.txt
. - Create a directory named
testdir
. - List all files and directories in the current directory.
Solution
Exercise 2: Copy and Move Files
- Copy
testfile.txt
totestfile_copy.txt
. - Move
testfile_copy.txt
totestdir/
.
Solution
Exercise 3: Remove Files and Directories
- Remove the file
testfile.txt
. - Remove the directory
testdir
(ensure it is empty first).
Solution
Summary
In this section, we covered the basic file and directory operations in Bash, including creating, listing, copying, moving, and removing files and directories. These commands are essential for managing the filesystem and will be used frequently in your Bash scripting journey.
Bash Programming Course
Module 1: Introduction to Bash
Module 2: Basic Bash Commands
- File and Directory Operations
- Text Processing Commands
- File Permissions and Ownership
- Redirection and Piping