getcwd - Linux
Overview
getcwd is a Linux command used to get the current working directory. It is a common utility for scripting and automation tasks where the current directory’s absolute path is needed.
Syntax
getcwd [options]
Options/Flags
| Option | Description | Default |
|—|—|—|
| –absolute | Print the absolute path | Yes |
| –logical | Resolve symbolic links and print the logical path | No |
| –help | Display usage information and exit | – |
| –version | Display version information and exit | – |
Examples
- Get the current working directory’s absolute path:
$ getcwd --absolute
/home/user/project
- Get the current working directory’s logical path:
$ getcwd --logical
/home/user/project/bin
- Use the output in a script:
#!/bin/bash
cwd=$(getcwd --absolute)
echo "Current directory: $cwd"
Common Issues
- Empty output: If no path is specified, getcwd will print nothing (an empty string).
- Incorrect path: The printed path may not be correct if the current working directory has changed after getcwd was called.
Integration
getcwd can be used in conjunction with other commands, such as:
- cd: Change the current working directory.
- ls: List the contents of the current directory.
- mkdir: Create a new directory.
Related Commands
- pwd: Print the current working directory in a more user-friendly format.
- realpath: Resolve symbolic links and print the absolute path.