Linux Shell Commands

This document provides a collection of useful shell commands for common tasks in Linux.

Process Management

Kill a Process by Name

PROCESS_NAME=ABC
pid=$(ps -ef | grep "$PROCESS_NAME" | grep -v grep | awk '{print $2}')
kill -9 "$pid"
  • Finds the PID of the process and kills it forcefully.
  • Caution: Use kill (without -9) first to allow graceful shutdown. Ensure the process name is unique to avoid killing unintended processes.

Start a Process as Daemon

nohup ./NAME &
  • Runs the command in the background and ignores hangup signals, keeping it running after logout.
  • Output is redirected to nohup.out by default.

Lookup Processes

ps -ef | grep PROCESS
  • Lists all processes and filters by name.

Stop a Process

kill -9 $pid
  • Forcefully terminates the process with the given PID.
  • Replace with kill $pid for a gentler stop.

Network Operations

Lookup Network Connections

ss -ntlp  # TCP listening ports
ss -nulp  # UDP listening ports
ss -antp  # All TCP connections

netstat -tnlp  # Alternative for TCP
netstat -nulp  # Alternative for UDP
  • ss is faster and preferred over netstat.

Test Network Connectivity

# Test TCP port (use nc for better security)
nc -zv host port

ping host
  • telnet is insecure; use nc (netcat) instead.

DNS Lookup

dig abc.com
dig abc.com @223.5.5.5  # Use specific DNS server (e.g., Alibaba DNS)
  • dig provides detailed DNS information.

File and System Operations

Find a File

sudo updatedb
locate filename
  • Updates the database first, then searches for files by name.
  • For real-time search: find /path -name filename

Additional Useful Commands

  • File Permissions: chmod 755 file, chown user:group file
  • Text Processing: grep "pattern" file, sed 's/old/new/' file, awk '{print $1}' file
  • System Info: df -h (disk usage), free -h (memory), uname -a (system info)
  • Archives: tar -czf archive.tar.gz dir, tar -xzf archive.tar.gz
  • Package Management (Ubuntu): sudo apt update, sudo apt install package

Best Practices

  • Use quotes around variables to handle spaces: grep "$VAR"
  • Run dangerous commands like kill -9 with caution.
  • For scripting, use #!/bin/bash and make scripts executable with chmod +x script.sh.
  • Learn man pages: man command for detailed help.

References