In this article, I will list commands that help interact with files and directories on a Linux system, along with the most common use cases. I write them down here as a short note. This article may be updated over time.
Print working directory
pwd
Change working directory
- Use an absolute path.
cd /var/log
- Use a relative path.
cd apt
I'm already in /var/log directory, it goes inside /var/log/apt
- Go to the user home directory.
cd
cd ~
- Go back the previous directory.
cd -
List items
- List items in the current directory.
ls
- List items in a specific directory.
ls /etc/
- Add more options to the ls command.
- -l: Use a long listing format.
- -a: Display all items including one starts with dot (.)
- -h: Display sizes in 1K, 2M, etc, which is easy to read.
- --group-directories-first: Display directories first, then files.
ls -lah --group-directories-first /etc/
Create an empty file
If hello.txt doesn't exist, it'll be created. Otherwise, it's modified time will be changed.
touch hello.txt
Copy
- Copy 1.txt to one.txt in the current directory.
cp 1.txt one.txt
- Copy one.txt to the /tmp directory.
cp one.txt /tmp
- Copy /var/log directory to /tmp directory.
cp -r /var/log /tmp/
- Copy /var/log to /tmp, and change it's name to cp-log.
cp -r /var/log /tmp/cp-log
Move or rename
- Rename hello.txt to hello-world.txt. If hello-world.txt exists, it'll be override.
mv hello.txt hello-world.txt
- Move a directory or file to new location.
mv hello-world.txt /tmp/
mv example /tmp/
Make directories
- Use -p option to create nested directories or keep silent if directories already exist.
mkdir example
mkdir -p example/foo/bar/baz
Remove directories or files
- Add -f option to force to remove without confirmation or raising errors if they does not exist.
rm hello.txt
rm -r greetings/
rmdir can only remove an empty directory, so I've never used it.
Top comments (0)