Linux cheatSheet for PHP developers
Text Processing Power Tools
Grep
- grep stands for "Global Regular Expression Print".
- It’s a command-line tool used to search for text patterns inside files or output.
grep "pattern" filename
Option | What it does |
---|
-i | Ignore case (e.g., Sunny = sunny) |
-v | Invert match (show lines not matching) |
-r/-R | Recursively search in directories |
-n | Show line numbers |
-H | Show the filename in the output (even if only one file is searched) |
-l | Show only filenames with matches |
-L | Show only the names of files without matches |
-c | Count matching lines |
-o | Print only the matched part of the line |
-w | Match whole words only |
-x | Match entire lines only |
-E | Use extended regular expressions (ERE) |
-F | Interpret pattern as a fixed string (no regex) |
-P | Interpret pattern as a Perl-compatible regex (PCRE; not available in all grep versions) |
--color=auto | Highlight matches in color (usually on by default in many distros) |
Find an installed (apt/snap) package/application
snap list
dpkg --get-selections
dpkg --get-selections | grep google
apt-mark showmanual
apt-mark showmanual | grep google
Examples
grep "ERROR" /var/log/app.log
grep -Hnir zend_extension /etc/php/8.2/
grep "string" file.log > result.log
grep -E "21:20:[0-5][0-9]] some text" file.log > result.log
tail -l 1000 | grep "string" fileName
print search result into a file
grep -E "21:20:[0-5][0-9]]some text" file.log > result.log
sed (stream editor)
What sed Does
- Reads input line by line
- Applies editing commands (like substitute, delete, insert, etc.)
- Outputs the modified text (usually to stdout)
sed [OPTIONS] 'COMMAND' [FILE]
sed 's/old/new/' file
echo "hello world" | sed 's/world/universe/'
sed 's/old/new/g' file
sed -i 's/old/new/g' file
sed -i.bak 's/old/new/g' file
sed '/pattern/d' file
sed -n '/pattern/p' file
sed '2s/foo/bar/' file
sed -n '/^START_TIME_PATTERN/,/^END_TIME_PATTERN/p' input_file > output_file
sed -n '/^21:19:[0-5][0-9]]/,/^21:21:[0-5][0-9]]/p' file.log > result.txt
awk
- awk is another powerful command-line tool like sed, but it’s better suited for working with structured text like columns in logs, CSVs, or space/tab-delimited data.
What is awk?
- awk is a text-processing language.
- It reads files line by line, splits lines into fields, and performs actions based on patterns.
- Ideal for column-based operations, filtering, summarizing, and reporting.
awk 'pattern { action }' file
awk '{print $1}' access.log
Finding Files or Directories by Name Using ls and find
Goal | Command | Matches |
---|
Exact match in current dir | ls -l test | Only test |
Starts with in current dir | ls -l test* | test, test1, testfile |
Exact match recursively | find . -name 'test' | Only test |
Starts with recursively | find . -name 'test*' | test, test123, etc. |
Case-insensitive recursive | find . -iname 'test*' | Test, TEST, etc. |
Process Management & System Monitoring
lsof
- lsof stands for List Open Files. In Linux, everything is a file, including sockets, devices, and network connections — and lsof shows which files are currently open by which processes.
Here’s a list of commonly used lsof flags, along with short explanations for each:
General Flags
Flag | Description |
---|
-h | Show help message |
-v | Show version and verbose info |
-n | Don't resolve hostnames (no DNS lookup) |
-P | Don't resolve port numbers to service names |
-i | Show network files (TCP, UDP, etc.) |
Filtering by Protocol / Address
Flag | Description |
---|
-i[proto] | Show only network files (optionally specify tcp, udp, etc.) |
-i :port | Filter by port number (e.g. -i :8000) |
-i @host | Filter by host IP (e.g. -i @127.0.0.1) |
-i @host:port | Filter by host and port |
Filtering by File or Process
Flag | Description |
---|
-p PID | Show files opened by specific process ID |
-u USER | Show files opened by specific user |
-c CMD | Filter by command name |
-t | Output only PIDs (useful for scripting) |
+D dir | Show all files under a directory (not recursive unless with +D) |
+d dir | Like +D, but not recursive |
Output Control
Flag | Description |
---|
-F | Output in parseable format (used in scripts) |
-s | Show file sizes |
-l | Show login names instead of user IDs |
Examples
lsof -i :8080
lsof -i [email protected]
lsof -p 1234
lsof -u www-data
lsof -t -i :3306
Kill by task id
lsof -n -P -i | grep 8000
kill -9 ID
Kill a Process by name
pkill firefox
pkill -u www-data php
pkill -f "php artisan queue:work"
pkill -x php
target specific processes
ps aux | grep firefox
kill PID
kill queue process in linux
ps -aux | grep queue
kill -9 8118
kill a serve on a port
kill $(lsof -t -i :PORT_NUMBER)
Linux file commands
append text to a file
echo "Your text here" >> filename.txt
Append Multiple Lines (using cat + here-doc)
cat <<EOF >> filename.txt
Line 1
Line 2
Line 3
EOF
Using tee with -a (append mode)
echo "Another line" | tee -a filename.txt
Append command output to a file
ls -l >> files.txt
head -n 10 file.txt x`(get 10 lines of files)
split --lines=100000 file.txt folder/(separate text file into parts)
wc -l file.txt(get number of lines in file)
.bashrc
- .bashrc is a shell script that runs every time a new terminal session is started in interactive mode (like when you open a terminal in Ubuntu).
- It’s where you customize your shell environment, including aliases, environment variables, prompt styles, and more.
Set Aliases (custom shortcuts)
alias ll='ls -alF'
alias art='php artisan'
alias serve='php -S localhost:8000'
Export Environment Variables
export APP_ENV=local
export PATH=$PATH:/opt/some/custom/bin
Show git branch name in the Terminal
force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^]/d' -e 's/ (.)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}[\033[01;32m]\u@\h[\033[00m]:[\033[01;34m]\w[\033[01;31m]$(parse_git_branch)[\033[00m]$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)$ '
fi
unset color_prompt force_color_prompt
Run Scripts or Commands at Startup
echo "Welcome back, $USER!"
Reload bashrc
- After you make changes to your .bashrc file, you need to reload it in the current shell session for the changes to take effect.
source ~/.bashrc OR . ~/.bashrc
Shell Scripting (Bash)
nano myscript.sh
chmod +x myscript.sh
./myscript.sh
for i in {1..5}; do
echo "Line $i"
done
File Permissions & Ownership
Linux File/Directory Permissions (Essentials)
- Every file/directory has 3 permission sets
Role | Who it applies to |
---|
User (u) | The file owner |
Group (g) | Users in the owner’s group |
Others (o) | Everyone else |
Permission Types: rwx
Symbol | Meaning | Applies to |
---|
r | read | Can view file content / list directory |
w | write | Can edit file / create/delete in dir |
x | execute | Can run file / enter directory |
Number System (Octal)
Each rwx combo is mapped to a number:
Permission | Binary | Value |
---|
r | 4 | 100 |
w | 2 | 010 |
x | 1 | 001 |
So:
- rwx = 4 + 2 + 1 = 7
- rw- = 4 + 2 = 6
- r-- = 4 = 4
- --- = 0 = 0
Example: chmod 755 file.sh
Breakdown of 755:
Who | Number | rwx | Meaning |
---|
User | 7 | rwx | Full access |
Group | 5 | r-x | Read & execute (but can't write) |
Others | 5 | r-x | Read & execute |
So: owner can modify and run, others can only view and run.
What does chmod 777 mean?
Role | rwx | Meaning |
---|
User | rwx | Can read, write, and execute |
Group | rwx | Can read, write, and execute |
Others | rwx | Can read, write, and execute |
- Huge security risk if used on web apps!
- Gives everyone full access — only use temporarily for debugging.
Common Commands
chmod 755 file.sh
chmod -R 775 storage/
chown user:group file
chmod a+rw file.txt
allow read and write permissions for all users
sudo chmod a+rw storage/logs/file.log
Package Management
List down all the installed apt packages
apt list --installed
snap package list
Upgrade specific apt package
sudo apt-get install --only-upgrade <packagename>
or
sudo apt update && sudo apt <packagename>
Ex: sudo apt update && sudo apt upgrade google-chrome-stable
Install a package
sudo apt install nginx
Update & upgrade
sudo apt update && sudo apt upgrade
Search for a package
apt search php
Upgrade snap packages
sudo snap refresh package_1 package_2
for greater detail, check
https://itsfoss.com/snap-update/
Installed location of an application
1. echo $PATH
2. sudo apt install mlocate
sudo updatedb
locate studio.sh
3. cd /usr/share/applications/
cat android-studio.desktop
Location is -> Exec=.
Linux Security & Hardening
Enable firewall
sudo ufw enable
Check firewall status
sudo ufw status
Ban IP with fail2ban
sudo fail2ban-client set sshd banip 1.2.3.4
Harden SSH access
sudo nano /etc/ssh/sshd_config
Copy linux directory
sudo cp -r /path/to/directory
mount directory as writable
sudo mount -o remount,rw /path/to/directory
Systemd & Services
Start a service
sudo systemctl start nginx
Enable at boot
sudo systemctl enable php7.4-fpm
Check status
sudo systemctl status apache2
PHP Server Management
Edit PHP config
sudo nano /etc/php/7.4/fpm/php.ini
Restart PHP service
sudo systemctl restart php7.4-fpm
Check logs
tail -f /var/log/nginx/error.log
Logs & Monitoring
View logs
tail -n 100 /var/log/syslog
Live logs
journalctl -f
Process monitor
htop
Deployment Tools
Copy files
rsync -avz ./site/ user@host:/var/www/site
SSH to server
ssh user@host
Automate deployment
nano deploy.sh