|
Shell provides several commands for working with
directories: Create a directory with |
|
|
Output:
Created /tmp/mydir mydir |
|
|
Create nested directories with |
|
|
Output:
Created nested directories: grandchild |
|
|
|
|
|
Remove empty directory with |
|
|
Output:
Removed /tmp/mydir |
|
|
Remove nested empty directories: |
|
|
Output:
Removed nested directories |
|
|
List directory contents with |
|
|
Output:
List directory: file1.txt file2.sh Detailed listing: total 0 drwxr-xr-x 2 root root 80 Jan 1 2025 . drwxrwxrwt 3 root root 60 Jan 1 2025 .. -rw-r--r-- 1 root root 0 Jan 1 2025 file1.txt -rw-r--r-- 1 root root 0 Jan 1 2025 file2.sh One file per line: file1.txt file2.sh |
|
|
Hidden files (start with |
|
|
Output:
Including hidden files: . .. .hidden |
|
|
Check if directory exists with |
|
|
Output:
/tmp/testdir exists |
|
|
Change directory with |
|
|
Output:
Changed to: /tmp/testdir Back to: /tmp |
|
|
Use subshell to avoid changing current directory: |
|
|
Output:
In subshell: /tmp/testdir Still in: /tmp |
|
|
Find files in directory with find: |
|
|
Output:
Find all files: /tmp/findtest/b.sh /tmp/findtest/a.txt /tmp/findtest/sub/c.txt Find only .txt files: /tmp/findtest/a.txt /tmp/findtest/sub/c.txt Find by type (directories): /tmp/findtest /tmp/findtest/sub |
|
|
Find with depth limit with |
|
|
Output:
Max depth 1: /tmp/findtest/file2.txt /tmp/findtest/file1.txt |
|
|
Find with |
|
|
Output:
Find files and list them: /tmp/findtest/file2.txt /tmp/findtest/file1.txt |
|
|
Find files by age with |
|
|
Output:
Files modified in last day: /tmp/findtest/file2.txt /tmp/findtest/file1.txt |
|
|
Directory size with |
|
|
Output:
Directory sizes: 4.0K /tmp/testdir 0 /tmp/findtest |
|
|
List subdirectory sizes with |
|
|
Output:
Subdirectory sizes: 0 /tmp/findtest |
|
|
Count files in directory with |
|
|
Output:
File count: 2 |
|
|
Iterate over directory contents with |
|
|
Output:
Loop over files: Found: file1.txt Found: file2.txt |
|
|
Safe handling of special characters: |
|
|
Output:
Files with spaces: /tmp/spaces dir/file with spaces.txt |
|
|
Copy directory with |
|
|
Output:
Copied directory: testdir |
|
|
Move/rename directory with |
|
|
Output:
Renamed to testdir_renamed |
|
|
Remove directory and contents with rm -r: |
|
|
Output:
Removed testdir_renamed |
|
|
Temporary directory: |
|
|
Output:
Created temp dir: /tmp/tmp.stab000000 |
|
|
Get home directory: |
|
|
Output:
Home directory: /root Tilde expansion: ~ |
|
|
Special directories: |
|
|
Output:
Current: /tmp Previous: not set |
|
|
Bash
Directory stack (pushd/popd) with error handling |
|
|
Output:
Pushed to: /tmp Pushed to: /var Popped to: /tmp |
|
|
Check for empty directory: |
|
|
Output:
/tmp/emptydir is empty |
|
|
Create directory only if it doesn’t exist: |
|
|
Output:
Ensured /tmp/ensured exists |
|
|
Cleanup test directories |
|
|
Output:
Directory examples complete |
|