-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasename_realpath_dirname
More file actions
81 lines (63 loc) · 2.09 KB
/
Copy pathbasename_realpath_dirname
File metadata and controls
81 lines (63 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
➜ Learning-ShellScripting git:(main) basename /mnt/c/Users/naras/OneDrive/Documents/Learning-ShellScripting/arg2.sh
arg2.sh
# gives file name
➜ Learning-ShellScripting git:(main) dirname /mnt/c/Users/naras/OneDrive/Documents/Learning-ShellScripting/arg2.sh
/mnt/c/Users/naras/OneDrive/Documents/Learning-ShellScripting
# gives directory name
In shell scripting, `realpath`, `basename`, and `dirname` are commonly used commands to manipulate file paths. Here’s how each of them works:
### 1. **`realpath`**
- **Purpose**: Returns the absolute path of a given file or directory.
- **Usage**:
realpath [file_or_directory]
```
- **Example**:
realpath ./myfile.txt
```
If you are in `/home/user/project` and `myfile.txt` is in the current directory, it will return:
```
/home/user/project/myfile.txt
```
### 2. **`basename`**
- **Purpose**: Extracts the filename or directory name from a given path.
- **Usage**:
basename [file_or_directory_path] [suffix]
```
- **Example**:
basename /home/user/project/myfile.txt
```
Output:
```
myfile.txt
```
If you use a suffix (e.g., `.txt`), it will strip the suffix:
```bash
basename /home/user/project/myfile.txt .txt
```
Output:
```
myfile
```
### 3. **`dirname`**
- **Purpose**: Extracts the directory path from a given file path.
- **Usage**:
dirname [file_path]
```
- **Example**:
dirname /home/user/project/myfile.txt
```
Output:
```
/home/user/project
```
### Use Case Example:
file_path="/home/user/project/myfile.txt"
# Get the absolute path
absolute_path=$(realpath "$file_path")
echo "Absolute Path: $absolute_path"
# Get the filename
filename=$(basename "$file_path")
echo "Filename: $filename"
# Get the directory name
directory=$(dirname "$file_path")
echo "Directory: $directory"
This script will output the absolute path, filename, and directory name separately.