Mastering Terminal Commands

💡
Inspired by Kunal Kushwaha's YouTube tutorials, this article explores networking protocols and internet infrastructure.

A terminal emulator is used to perform operations on the operating system through textual commands.

Commands entered are case-sensitive, distinguishing between uppercase and lowercase characters.

The shell acts as a command interpreter, processing commands entered by users and executing them within the operating system. Common shell versions include zsh and bash.

Commands like which are used to locate the location of applications or files within the system.

An environment variable functions as a special note that instructs the computer on how to perform certain tasks, such as specifying which folders to search or what colors to use. These variables store information such as system paths, user preferences, and configuration settings, accessible during program execution. They can be set, modified, and retrieved by the operating system and applications to customize behavior and provide necessary resources.

For instance, when a user types python3, the system searches for the Python interpreter in directories specified by the PATH environment variable. This ensures the system can locate and execute essential programs irrespective of the current working directory.

  • To locate the path of an application or file within the system, users employ commands such as:

      which python3
    

    This command displays the directories listed in the echo $PATH environment variable, which specifies where the operating system looks for executable files.

  • Opening a terminal emulator triggers the automatic execution of certain files, such as bash files. For instance, configuring themes or colors can be automated through scripts.

  • The cat command is used to display the contents of a file. For example:

      cat ali.txt
    

    This command would show the contents of the file ali.txt.

  • Additionally, the alias command is used to create shortcuts for frequently used commands.

      alias ll='ls -al'
    
  • Files that start with a . are considered hidden files in Unix-like systems. These files are typically configuration files or files meant for system use.

  • In Unix-like operating systems like Linux and macOS, the export command is used to define environment variables.

      export PATH=$PATH:/new/path
    
  • Commands like . represent the current directory, while .. denotes the parent directory. The -l option with commands like ls provides detailed information about file such as permissions, owner, group, size, and modification date.

      ls -al
    

    Including hidden ones:

      ls -a
    
  • The cd command is used to change directories. For instance:

      cd ..
    

    This command would navigate to the previous directory.

  • The -R option with commands like ls recursively lists files and directories, including those in subdirectories.

      ls -R
    

    By default, ls -R starts listing from the current directory (.).

  • The cat > command is used to create a new file with specific content. For example:

      cat > imran.txt
    

    This command creates a file named imran.txt with the specified content.

  • In Unix systems, > redirects command output, overwriting the file:

      echo "new content" > who.txt
    

    >> appends output:

      echo "additional content" >> who.txt
    
  • The man command is used to display the manual page for a command, providing detailed information about its usage and options.

      man ls
    
  • The tr command translates characters, such as converting lowercase letters to uppercase. For example:

      tr 'a-z' 'A-Z' < pti.txt > who.txt
    

    This command translates the contents of pti.txt from lowercase to uppercase and saves the output to who.txt.

  • In Linux/Unix command line usage, the > symbol is employed for output redirection. This functionality allows users to redirect the output of a command to a file instead of displaying it in the terminal.

      ls > filelist.txt
    

    Additionally, the pipe symbol | is used to connect the output of one command as the input to another command. For example:

      history | grep "ls"
    

    Here, grep receives the output of ls as its input.

    To append new content to a file on a new line using output redirection, Linux/Unix utilizes the double greater-than symbol >> instead of the single >. This ensures that new content is added to the file without overwriting existing content.

    Other essential commands include:

    • mkdir -p: Creates directories, including parent directories if they do not already exist.

        mkdir -p newdir/subdir
      
    • touch oo/l.txt: Creates a file named l.txt within the oo directory.

        touch oo/l.txt
      
    • . symbol: Represents the current directory in Linux.

        cd .
      
    • cp text1.txt copytext1.txt: Copies text1.txt to copytext1.txt.

        cp text1.txt copytext1.txt
      
    • mv [options] source destination: Moves files or directories from one location to another, also used to rename files and directories.

    • If you have a file named oldname.txt and you want to rename it to newname.txt, you would execute the following command:

        mv file1.txt /path/to/new_directory/
      
    • rm: Removes files (not for directories). To delete directories, use rm -r. For forceful removal, rm -rf.

        rm file.txt
        rm -r directory
        rm -rf directory forceful
      
    • cp: Copies files and directories. Use cp -r to copy directories recursively. Without the -r option, cp would only copy individual files, not directories or their contents.

        cp -r sourcedir destdir
      
    • sudo: Executes commands with superuser privileges.

        sudo apt update
      
    • df: The df command displays the amount of disk space available and used on filesystems.

        df -m
      
    • du: Shows disk usage, indicating the space used by files and directories.

        du
      
    • vi filename: Opens the filename in the vi text editor.

        vi filename
      

In vi, the command usage includes:

  1. Insert mode: Press i to enter insert mode, allowing text insertion. Press Esc to exit insert mode.

  2. Saving and quitting: Use :wq to save changes and quit, or :q! to quit without saving.

Understanding these commands enhances proficiency in navigating and managing files and directories in Linux/Unix environments

  • head: Displays the top 10 lines of a file by default.

      head filename
    

    To display a specific number of lines, use:

      head -n 5 filename
    
  • tail: Shows the bottom 10 lines of a file by default.

      tail filename
    
  • Locate command: Quickly finds files based on name.

      locate filename
    

    This command is fast and useful for quick searches.

  • Find command: More powerful but slower than locate. Can search based on various attributes like name, size, type, owner, permissions, and modification time.

      find /path -name filename
    
  • File permissions: Represented by ls -l, which displays permissions for files and directories.

      ls -l
    
  • Changing file permissions: Done with chmod command.

      chmod 755 filename
    
  • Ownership: Change file ownership with chown.

  • sudo: Super user group (g)

  • users: Simple user (u)

  • other: All other people (o)

  • user: Specifies the new owner of the file or directory.

  • group: Specifies the new group ownership.

      chown user:group filename
    
  • User identification: To check the current user, use whoami.

      whoami
    

In Linux/Unix command line operations, several commands are essential for file management and searching:

  1. Finding files with specific permissions: Use find with the -perm option to locate files with specific permissions.

     find . -perm 777
    

    This command searches recursively from the current directory (.) for files with permissions set to 777.

  2. Executing commands with-exec: The -exec option allows executing a command for each file found by find.

     find . -name "*.txt" -exec rm -rf {} \;
    

    Here, find searches for .txt files and deletes them (rm -rf) using -exec. The {} placeholder represents each file found, terminated by \;.

  3. Searching within files usinggrep:

     grep "wordtofind" filename
    
    • To find occurrences of a word (wordtofind) in a file (filename):

    • Options for grep:

      • -w: Matches whole words only.

          grep -w "wordtofind" filename
        
      • -i: Performs case-insensitive search.

          grep -i "wordtofind" filename
        
      • -n: Displays line numbers containing the search term.

          grep -n "wordtofind" filename
        
      • -B: Shows lines before the matched line.

          grep -B 2 "wordtofind" filename
        
  1. Recursive search (grep -r): Searches through all subdirectories (-r) for files containing a specific word.

     grep -r "saba" ./*.txt
    
    • Example shows searching for saba in all .txt files within the current directory (./).
  2. Printing filenames (-l) and counting matches (-c):

     grep -l "saba" ./*.txt
     grep -c "saba" ./*.txt
    
    • -l: Prints filenames of matching files.

    • -c: Counts occurrences of the search term.

  3. Viewing command history:

     history
    
    • Lists the command history of the current session.

    • Example:

        history | grep "ls"
      

      Displays history entries containing ls.

  4. Aliases: Shortcuts for commands.

     alias ll='ls -al'
    
    • Aliases simplify command execution.

    • Example:

        alias ll='ls -al'
      
  5. Keyboard Shortcuts:

    • Ctrl + a: Move the cursor to the beginning of the line.

    • Ctrl + l: Clear the terminal.

    • Ctrl + Alt + T: Open a new terminal window.

    • Ctrl + Shift + Plus (+): Increase the terminal window size.

    • Ctrl + Shift + Minus (-): Decrease the terminal window size.

    • Ctrl + e: Move the cursor to the end of the line.

    • Ctrl + k: Delete everything after the cursor.

    • Up and down arrow keys: Scroll through previous commands.

    • !number: Execute a specific command from history by its number..

        !42
      
  6. Running Multiple Commands: Use semicolons to run multiple instructions in a single line:

     command1; command2; command3
    
  7. Sorting Files:

    • sort: Sorts lines in a file alphabetically.

        sort filename
      
    • sort -r: Sorts in reverse order.

        sort -r filename
      
    • sort -n: Sorts numerically.

        sort -n filename
      
    • sort -f: Ignores case sensitivity.

        sort -f filename
      
  8. Network Utilities:

    • Ping: Tests connectivity to a device on an IP-based network.

    • Ping, like testing a website's response time by sending packets and receiving responses, assesses network connectivity and performance.

        ping google.com
      
  9. Package Management:

    • sudo apt install: Installs packages on Debian-based Linux systems.

        sudo apt install package_name
      
  10. Downloading Files:

    • Wget: Downloads files from the internet directly to the active directory. link should be in double quotes.

        wget http://example.com/file.zip
      
  11. Downloading Files withwget:

    • wget [URL]: Downloads files from a URL.

        wget http://example.com/file.zip
      
    • wget -O [custom_filename] [URL]: Saves the downloaded file with a custom name.

        wget -O custom_name.zip http://example.com/file.zip
      
  12. Monitoring Processes withtop:

    • top: Displays active processes and their resource usage.

        top
      
    • Use q to quit the top utility.

  13. Managing Processes withkill:

    • kill [PID]: Terminates a process identified by its process ID.

        kill 1234
      
  14. User Information:

    • whoami: Displays the current username.

        whoami
      
    • uname: Provides system information like kernel name, release, version, machine, and processor details.

        uname -a
      
  15. File and Directory Operations:

    • pwd: Prints the current working directory.

        pwd
      
    • zip: Compresses files into a zip archive.

        zip archive.zip file1 file2
      
    • unzip: Extracts files from a zip archive.

        unzip archive.zip
      
  16. Networking Commands:

    • hostname: Displays the device's network hostname.

        hostname
      
    • Loopback address (127.0.0.1) is used for local testing and inter-process communication.

  17. User Management:

    • sudo useradd [username]: Adds a new user.

        sudo useradd newuser
      
    • sudo userdel [username]: Deletes a user.

        sudo userdel olduser
      
  18. System Information:

    • cat /etc/os-release: Shows operating system details.

        cat /etc/os-release
      
    • lscpu: Provides detailed CPU information.

        lscpu
      

List Open Files:

  • lsof: Lists open files along with the processes that have them open.

      lsof
    

Find IP Address:

  • nslookup [domain]: Resolves and displays the IP address associated with a domain name.

      nslookup example.com
    

netstat Command:

  • Displays Active Connections: netstat shows all active TCP/UDP connections, including local and remote IP addresses and port numbers.

      netstat -an
    

cut Command:

  • cut -c [range] [filename]: Extracts specific columns (characters) from a file.

      cut -c 1-5 filename
    

Background Execution with &:

  • The & symbol is used to run commands in the background, allowing users to continue using the terminal while the command executes.

      command &
    

Logical Operators:

  • &&: Executes the second command only if the first command succeeds.

      command1 && command2
    
  • ||: Executes the second command only if the first command fails.

      command1 || command2
    

File Redirection:

  • >: Overwrites the contents of a file with the output of a command.

      echo "new content" > file.txt
    
  • >>: Appends the output of a command to the end of a file.

      echo "additional content" >> file.txt
    

Negate Command with !:

  • ! [command]: Negates the command, useful for conditionals or logical checks

      ! ls
    

#linux # command line #OS