Shell Commands Cheatsheet for Linux and macOS
List of Shell Commands#
ls to list the files and directories in the current directory#
ls
# List all files and directories including hidden files
ls -a
# List files and directories with detailed information
ls -l
# List all files and directories with detailed information including hidden files
ls -la
cd to change the current directory.#
cd path/to/directory
pwd#
pwd command is used to print the current working directory.
pwd
mkdir#
mkdir command is used to create a new directory.
mkdir new-directory
touch#
touch command is used to create a new file.
touch new-file.txt
rm#
rm command is used to remove files or directories.
rm file.txt
cp#
cp command is used to copy files or directories.
cp file.txt new-file.txt
mv#
mv command is used to move files or directories.
mv file.txt path/to/directory
cat#
cat command is used to display the contents of a file.
cat file.txt
grep#
grep command is used to search for a specific pattern in a file.
grep 'pattern' file.txt
echo#
echo command is used to print text to the terminal.
echo 'Hello, World!'
chmod#
chmod command is used to change the permissions of a file or directory.
chmod 755 file.txt
chown#
chown command is used to change the owner of a file or directory.
chown user:group file.txt
ps#
ps command is used to display information about running processes.
ps
kill#
kill command is used to terminate a process.
kill PID
top#
top command is used to display information about running processes in real-time.
top
Redirect terminal output to a file#
Instead of printing the output to the terminal, you can redirect it to a file:
command > file.txt
# example
ls -l > output.txt
- Append insted of overwrite
command >> file.txt
# example
ls -la >> output.txt
lsof to find what's using a port#
lsof lists open files, including network ports. Useful when you get "port already in use" errors.
# Show what's running on port 3000
lsof -i :3000
# List all ports that are listening
lsof -iTCP -sTCP:LISTEN -P -n
Kill a process on a port#
kill $(lsof -t -i :3000)
# Force kill if it doesn't stop
kill -9 $(lsof -t -i :3000)
# Or without lsof
npx kill-port 3000
htop#
htop is an interactive alternative to top with filtering and easier process killing.
htop
# F4 to filter, F9 to kill the selected process