Nice 👌 this screenshot is showing three very useful Linux commands for working with file paths. Let’s break them down with examples:
- Removes the directory part of a path and only shows the file name.
basename /home/user/docs/report.txtOutput:
report.txt
You can also remove the file extension:
basename /home/user/docs/report.txt .txtOutput:
report
- Removes the filename and gives the directory path.
dirname /home/user/docs/report.txtOutput:
/home/user/docs
- Shows the absolute full path of a file.
- Useful if you are in a relative directory.
cd /home/user/docs
realpath report.txtOutput:
/home/user/docs/report.txt
Yes 👍 there are many more path and filename related commands/utilities in Linux (apart from basename, dirname, realpath). These are super useful when writing shell scripts. Let me give you a list with examples:
- Prints the absolute path of a symlink or file.
readlink -f myfileOutput:
/home/user/project/myfile
- Shows the current working directory.
pwdOutput:
/home/user/docs
- Can be used to print directory path only.
ls -d /etc/*- Shows detailed information about a file (size, permissions, last modified, etc).
stat report.txt- Identifies the file type (text, binary, image, etc).
file script.shOutput:
script.sh: Bourne-Again shell script, ASCII text executable
- Locate files or directories by name/path/size.
find /home/user -name "*.txt"- Get relative path instead of full absolute path.
realpath --relative-to=/home/user /home/user/docs/file.txtOutput:
docs/file.txt
You don’t always need external commands like basename. Bash itself can handle this:
#!/bin/bash
FILE="/etc/.nginx/nginx.conf"
echo "${FILE##*/}" # basename -> nginx.conf
echo "${FILE#*/}" # etc/.nginx/nginx.conf
echo "${FILE%/*}" # dirname -> /etc/.nginx
echo "${FILE%%/*}" #
echo "${FILE##*.}" # extension-> conf
echo "${FILE#*.}" # nginx/nginx.conf
echo "${FILE%.*}" # filename without extension -> /etc/.nginx/nginx
echo "${FILE%%.*}" # /etc/👉 So apart from basename, dirname, and realpath, the important related ones are:
readlinkpwdstatfilefind- Bash parameter expansion (
##,%operators)
Do you want me to prepare a cheatsheet table with all these commands + examples (like your screenshot style)?
👉 Do you want me to also show how you can combine these commands in a script (for example, to check a file’s path and name separately)?