linux

My Useful Shell Functions

Commandline Shell Functions that makes your workflow more productive

I use the command line for most daily work: creating files, moving around directories, editing with vim. Over time I’ve collected a handful of shell functions that save real time. Here are the ones I still use.

Viewing CSV Files in a Better Format

bash
function view_csv_pretty {    if [ -z "$1" ]; then        echo "Usage: view_csv_pretty <file.csv>"    else        cat "$1" | column -s, -t | less -F -S -X -K    fi}

This function comes in handy for viewing csv files directly in the terminal. Here’s what it does:

  1. cat "$1": Reads the content of the specified CSV file.
  2. column -s, -t: Uses the column command to format the content into a table
    1. -s,: Specifies that columns are separated by commas in the CSV file.
    2. -t: Tells column to create the table output.
  3. less -F -S -X -K:
    1. less: Displays the formatted table output in the terminal.
    2. -F: Quits if the entire file fits on one screen.
    3. -S: Chops long lines to fit within the screen width.
    4. -X: Leaves the screen’s contents intact upon exiting less
    5. -K: Exits less on Ctrl+C.

Checking Recently Modified Files

recently_modified is one my team uses to keep track of the latest change to files on the server.

bash
function recently_modified() {    recent_file=$(ls -t | head -n1)    echo "Most recently modified file: $recent_file"}

Compressing Multiple Files

bash
function compress_files() {    if [ -z "$1" ]; then        echo "Usage: compress_files <archive_name.zip> <file1> <file2> ..."    else        zip -r "$1" "${@:2}"    fi}

Searching text in files

bash
function search_text_in_files() {    if [ -z "$1" ] || [ -z "$2" ]; then        echo "Usage: search_text_in_files <directory> <search_term>"    else        grep -rnw "$1" -e "$2"    fi}

Checking high usage memory processes

bash
function process_with_most_memory() {    ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head}

Listing Open Ports

bash
function list_open_ports() {    netstat -tuln}

Listening Ports for specific process

bash
function  find_listening_ports() {    if [ -z "$1" ]; then        echo "Usage: find_listening_ports <pid>"    else        ss -tulnp | grep "$1"    fi}

If you have a favorite shell function of your own, share it in the comments, or send me an email.


If you loved this post, you can always support my work by buying me a coffee. Your support would mean the world to me! Also, if you end up sharing this on Twitter, definitely tag me @muhammad_o7.

Want new posts in your inbox? Subscribe by email or follow the RSS feed.