Top 10 Lesser-Known but Useful Linux Terminal Commands

Posted on:July 21, 2024 at 02:22

As someone who spends a fair amount of time in the Linux terminal, I often stumble upon commands that are less talked about but incredibly useful. I’ve put together this list as a reminder of some essential yet often overlooked commands and their powerful sub-options. Whether you’re new to Linux or a seasoned user, I hope you find these as helpful as I have in making working in terminal more efficient.

1. tree - Display Directory Structure

The tree command provides a visual representation of your directory structure, making it easy to understand the hierarchy of your files and folders.

Installation:

Examples:

  1. Basic usage:

    tree

    Output:

    .
    ├── folder1
    │   ├── file1.txt
    │   └── file2.txt
    └── folder2
        └── file3.txt
  2. Limit depth:

    tree -L 2

    Output:

    .
    ├── folder1
    │   ├── subfolder1
    │   └── subfolder2
    └── folder2
        └── subfolder3
  3. Show only directories:

    tree -d

    Output:

    .
    ├── folder1
    │   └── subfolder1
    └── folder2
  4. Show hidden files:

    tree -a

    Output:

    .
    ├── .hidden_folder
    │   └── .hidden_file.txt
    ├── folder1
    │   └── file1.txt
    └── folder2
        └── file2.txt
  5. Advanced: Combine options and use patterns:

    tree -L 2 -P '*.txt' --prune

    Output:

    .
    ├── folder1
    │   ├── file1.txt
    │   └── file2.txt
    └── folder2
        └── file3.txt

Why it’s useful:

2. ncdu - Analyze Disk Usage

Short for “NCurses Disk Usage,” ncdu is an interactive disk usage analyzer that helps you identify which files and directories are consuming the most space on your system.

Installation:

Examples:

  1. Basic usage:

    ncdu

    (Interactive ncurses interface showing disk usage)

  2. Scan a specific directory:

    ncdu /home/user

    (Interactive ncurses interface showing disk usage for /home/user)

  3. Export results to file:

    ncdu -o ncdu_output.json /home/user

    (No visual output, but creates ncdu_output.json)

  4. Read from exported file:

    ncdu -f ncdu_output.json

    (Interactive ncurses interface showing disk usage from the file)

  5. Advanced: Exclude certain file types:

    ncdu -X '*.log' -X '*.tmp' /var/log

    (Interactive ncurses interface showing disk usage, excluding .log and .tmp files)

Why it’s useful:

3. htop - Interactive Process Viewer

While top is a well-known command for monitoring system processes, htop takes it to the next level with its interactive and colorful interface.

Installation:

Examples:

  1. Basic usage:

    htop

    (Interactive process viewer)

  2. Show only processes of a specific user:

    htop -u username

    (Interactive process viewer showing only processes of ‘username’)

  3. Start with processes sorted by CPU usage:

    htop -s PERCENT_CPU

    (Interactive process viewer with processes sorted by CPU usage)

  4. Tree view:

    htop -t

    (Interactive process viewer in tree view mode)

  5. Advanced: Custom meter configuration:

    htop --no-color --delay=30 --sort-key=PERCENT_MEM

    (Interactive process viewer without color, 30-second delay, sorted by memory usage)

Why it’s useful:

4. pv - Monitor the Progress of Data Through a Pipe

The pv (Pipe Viewer) command allows you to see the progress of data flowing through a pipeline, which is especially useful for long-running operations.

Installation:

Examples:

  1. Basic usage: Monitor file copy

    pv largefile.iso > copiedfile.iso

    Output:

     2.05GB 0:00:30 [68.3MB/s] [====>      ] 41% ETA 0:00:43
  2. Use with compression:

    pv largefile.tar | gzip > largefile.tar.gz

    Output:

     1.23GB 0:00:45 [28.1MB/s] [=========>  ] 78% ETA 0:00:12
  3. Monitor multiple files:

    pv file1 file2 file3 > combined_file

    Output:

    file1:  523MB 0:00:05 [104MB/s] [==========] 100%
    file2:  217MB 0:00:02 [108MB/s] [==========] 100%
    file3:  1.05GB 0:00:15 [71.2MB/s] [====>    ] 42% ETA 0:00:20
  4. Rate limiting:

    pv -L 1m largefile.iso > destination.iso

    Output:

     52.4MB 0:00:52 [1.00MB/s] [    <=>     ] 2% ETA 0:41:08
  5. Advanced: Custom format and numeric output:

    pv -n largefile.iso | gzip > largefile.iso.gz 2>&1 | \
    awk '{printf "\rCompressed: %d%% (%d/%d MB)", $2, $1/1024/1024, $3/1024/1024}'

    Output:

    Compressed: 45% (1024/2048 MB)

Why it’s useful:

5. watch - Execute a Program Periodically

The watch command allows you to run a specified command repeatedly, showing the output in real-time. This is particularly useful for monitoring changing data or system status.

Examples:

  1. Basic usage: Monitor system uptime

    watch uptime

    Output (refreshes every 2 seconds):

     22:14:32 up  3:27,  2 users,  load average: 0.08, 0.03, 0.05
  2. Custom interval: Check disk usage every 5 seconds

    watch -n 5 df -h

    Output (refreshes every 5 seconds):

    Filesystem      Size  Used Avail Use% Mounted on
    /dev/sda1        30G   15G   14G  52% /
    /dev/sdb1       100G   60G   35G  63% /home
  3. Highlight differences

    watch -d free -m

    Output (refreshes every 2 seconds, changes highlighted):

                  total        used        free      shared  buff/cache   available
    Mem:           7965        3435        2789         541        1740        3735
    Swap:          2047           0        2047
  4. Run until a specific time

    watch -t -n 60 -c 'date; echo "Server running..."; uptime' | ts '[%Y-%m-%d %H:%M:%S]' | tee -a server_log.txt

    Output (appends to server_log.txt):

    [2024-07-21 22:15:00] Sun Jul 21 22:15:00 UTC 2024
    [2024-07-21 22:15:00] Server running...
    [2024-07-21 22:15:00]  22:15:00 up  3:28,  2 users,  load average: 0.10, 0.04, 0.05
  5. Advanced: Watch a complex command

    watch 'ps aux | sort -nrk 3,3 | head -n 5'

    Output (refreshes every 2 seconds):

    USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
    user1     3423  2.5  1.2 234568 62344 ?        Sl   20:30   0:45 /usr/bin/gnome-shell
    root      1234  1.8  0.5 123456 23456 ?        Ss   20:25   0:30 /sbin/init
    user2     5678  1.5  0.8 345678 45678 ?        R    21:00   0:15 /usr/bin/firefox
    user1     7890  1.2  0.6 234567 34567 ?        S    20:35   0:20 /usr/bin/thunderbird

Why it’s useful:

6. tee - Read from Standard Input and Write to Standard Output and Files

The tee command reads from standard input and writes to both standard output and one or more files simultaneously. This is incredibly useful for logging command output while still displaying it on the screen.

Examples:

  1. Basic usage: Output to both file and screen

    echo "Hello, World!" | tee output.txt

    Output on screen:

    Hello, World!

    (Also written to output.txt)

  2. Append to existing file

    echo "New line" | tee -a output.txt

    Output on screen:

    New line

    (Appended to output.txt without overwriting)

  3. Write to multiple files

    echo "Multi-file output" | tee file1.txt file2.txt file3.txt

    Output on screen:

    Multi-file output

    (Also written to file1.txt, file2.txt, and file3.txt)

  4. Use with sudo to write to protected files

    echo "Root-level change" | sudo tee -a /etc/someconfigfile

    Output on screen:

    Root-level change

    (Appended to /etc/someconfigfile with root permissions)

  5. Advanced: Combine with other commands in a pipeline

    ls -l | tee file_list.txt | grep "\.txt$" | tee text_files.txt

    Output on screen: (list of .txt files) (Full directory listing saved to file_list.txt, .txt files list saved to text_files.txt)

Why it’s useful:

7. xargs - Build and Execute Command Lines from Standard Input

The xargs command is a powerful tool that allows you to build and execute command lines from standard input. It’s particularly useful when you need to run a command on a large number of files or inputs.

Examples:

  1. Basic usage: Process list of files

    echo "file1.txt file2.txt file3.txt" | xargs rm

    Output: (No output, files are removed)

  2. Use with find command

    find . -name "*.log" | xargs gzip

    Output: (No output, all .log files in current directory and subdirectories are compressed)

  3. Specify maximum number of arguments

    echo "1 2 3 4 5 6" | xargs -n 2 echo

    Output:

    1 2
    3 4
    5 6
  4. Use custom delimiter

    echo "name:John age:30 city:NewYork" | xargs -d ' ' -n 1 echo

    Output:

    name:John
    age:30
    city:NewYork
  5. Advanced: Parallel execution

    find . -name "*.jpg" | xargs -P 4 -I {} convert {} {}.png

    Output: (No output, converts jpg files to png using 4 parallel processes)

Why it’s useful:

8. nl - Number Lines of Files

The nl command is used to number the lines of a file. While simple, it can be incredibly useful for adding line numbers to scripts, log files, or any text file where you need to reference specific lines.

Examples:

  1. Basic usage: Number all lines

    echo -e "First line\nSecond line\nThird line" | nl

    Output:

         1  First line
         2  Second line
         3  Third line
  2. Number only non-empty lines

    echo -e "First line\n\nThird line" | nl -b a

    Output:

         1  First line
    
         2  Third line
  3. Custom numbering format

    echo -e "A\nB\nC" | nl -n rz -w 3

    Output:

    001  A
    002  B
    003  C
  4. Start numbering from a specific number

    echo -e "X\nY\nZ" | nl -v 10

    Output:

        10  X
        11  Y
        12  Z
  5. Advanced: Custom separators and selective numbering

    echo -e "# Comment\nCode line 1\n# Another comment\nCode line 2" | nl -b p'^[^#]'

    Output:

    # Comment
         1  Code line 1
    # Another comment
         2  Code line 2

Why it’s useful:

9. at - Schedule Commands to Run Once at a Particular Time

The at command allows you to schedule jobs to run once at a specified time. This is different from cron jobs, which are for recurring tasks.

Installation:

Note: After installation, you may need to enable and start the atd service:

sudo systemctl enable atd
sudo systemctl start atd

Examples:

  1. Basic usage: Schedule a simple task

    echo "echo 'Hello from the future!'" | at 16:30

    Output: job 1 at Wed Jul 21 16:30:00 2024

  2. Schedule a task for a future date

    echo "mail -s 'Report Ready' [email protected] < /tmp/report.txt" | at 9:00 AM Jul 25

    Output: job 2 at Sun Jul 25 09:00:00 2024

  3. Use a file as input for commands

    at -f backup_script.sh 2:00 AM tomorrow

    Output: job 3 at Thu Jul 22 02:00:00 2024

  4. Schedule a task to run after a delay

    echo "reboot" | sudo at now + 30 minutes

    Output: job 4 at Wed Jul 21 17:15:00 2024

  5. Advanced: Combine with output redirection and error handling

    at 23:00 <<EOF
    long_running_script.sh > /tmp/output.log 2>&1
    if [ $? -eq 0 ]; then
        echo "Script succeeded" | mail -s "Script Status" [email protected]
    else
        echo "Script failed" | mail -s "Script Status" [email protected]
    fi
    EOF

    Output: job 5 at Wed Jul 21 23:00:00 2024

Why it’s useful:

10. script - Make a Typescript of Terminal Session

The script command creates a typescript of everything displayed on your terminal. It’s an excellent tool for recording your terminal sessions, which can be useful for documentation, training, or troubleshooting.

Examples:

  1. Basic usage: Record a session

    script my_session.log
    # (Perform your terminal operations)
    exit

    Output: Script done, file is my_session.log

  2. Append to an existing log file

    script -a existing_log.log
    # (Perform more terminal operations)
    exit

    Output: Script done, file is existing_log.log

  3. Record with timing data

    script -t 2>timing.log session.log
    # (Perform terminal operations)
    exit

    Output: Script done, file is session.log

  4. Replay a recorded session

    scriptreplay timing.log session.log

    Output: (Replays the recorded session in real-time)

  5. Advanced: Record a non-interactive command

    script -c "find / -name '*.txt'" -q found_txt_files.log

    Output: (No output to terminal, all is recorded in found_txt_files.log)

Why it’s useful:

Command-line exploration

These ten lesser-known Linux terminal commands can significantly enhance your productivity and efficiency when working with the command line. From visualizing directory structures with tree to scheduling one-time tasks with at, each of these commands serves a unique purpose that can streamline your workflow.

By incorporating these tools into your daily routine, you’ll be able to manage your system more effectively, troubleshoot issues more quickly, and gain deeper insights into your Linux environment. Remember, the power of Linux lies in its versatility and the wealth of tools at your disposal. Don’t hesitate to explore man pages and experiment with these commands to discover even more ways they can benefit your work.

Whether you’re a system administrator, developer, or enthusiastic Linux user, mastering these commands will elevate your command-line skills and make you a more proficient power user. So fire up your terminal, start practicing, and watch your productivity soar!

Remember, while these examples provide a good starting point, each command has many more options and use cases. Always refer to the man pages (man command_name) for comprehensive documentation and additional features.

Happy command-line exploration!