Posts tagged with “bash”

Simplify MySQL Connections with a Smarter Bash Function

Working with multiple MySQL environments is a common scenario for developers. Whether you're connecting to development, staging, or production databases, you often need different connection parameters for each environment. While MySQL's configuration files help manage these connections, switching between them can be cumbersome. Let me introduce a simple but powerful bash function that will streamline this process.

The Problem

If you work with MySQL regularly, you likely have multiple connection profiles defined in your ~/.my.cnf file using the [group] syntax. To use a specific configuration group, you need to use the --defaults-group-suffix option:

mysql --defaults-group-suffix=dev
mysql --defaults-group-suffix=prod

This works, but it's verbose and typo-prone.

The Solution: A Smarter Bash Function

Here's a bash function that makes working with MySQL much more convenient:

m() {
    if [ $# -eq 0 ]; then
        # If no arguments provided, run mysql directly
        mysql
    elif [[ "$1" == -* ]]; then
        # If first argument starts with -, pass all arguments directly to mysql
        mysql "$@"
    else
        # Otherwise, treat first argument as suffix
        local suffix=$1
        shift
        mysql --defaults-group-suffix=$suffix "$@"
    fi
}

How It Works

This function provides three different behaviors depending on how you call it:

  1. No arguments: Simply runs the MySQL client with default settings.

    m
    
  2. First argument starts with a dash: Passes all arguments directly to MySQL, just like you're using the mysql command.

    m -e "SHOW DATABASES"
    
  3. First argument doesn't start with a dash: Uses the first argument as the defaults-group-suffix and passes the remaining arguments to MySQL.

    m dev -e "SELECT * FROM users"
    

Practical Examples

Example 1: Connect to Different Environments

m dev    # Connect to development database
m prod   # Connect to production database
m stage  # Connect to staging database

Example 2: Run Commands Directly

m dev -e "SELECT COUNT(*) FROM orders"
m prod -N -e "SELECT id FROM customers LIMIT 5"  # -N removes column names

Example 3: Use MySQL Options Directly

m -N -e "SELECT VERSION()"  # Quick query without environment prefix
m -t -e "SHOW TABLES"  # Table format output

Setup Instructions

  1. Add the function to your .bashrc or .zshrc file.
  2. Set up your MySQL configuration groups in ~/.my.cnf:
[client]
# Default settings

[clientdev]
user=devuser
password=devpass
host=dev-db.example.com

[clientprod]
user=produser
password=prodpass
host=prod-db.example.com

[mysql]
database=YourDataBase
  1. Source your shell configuration file or restart your terminal.

Benefits

  • Brevity: No need to type connection parameters (-h, -u, -p) repeatedly, as they're stored in your config file.
  • Flexibility: Pass any MySQL options like -N (skip column names) or -e (execute) alongside environment selection.
  • Consistency: Maintain the standard MySQL command syntax for direct option usage.

This simple function has saved me countless keystrokes and made database work significantly smoother. It's especially handy for running quick queries with options like -e (execute) and -N (no headers) without having to type connection details every time. Give it a try in your workflow—small improvements like this add up to a much more efficient development experience!

Do you have any favorite shell functions that make your development life easier? Share them in the comments!

AI Prompt for Git Commit Messages

Analyze the following code changes and generate a concise, meaningful git commit message that:

1. Summarizes the main purpose or impact of the changes
2. Is no longer than 100 characters (150 characters maximum if absolutely necessary)
3. Uses present tense and imperative mood (e.g., "Add feature" not "Added feature")
4. Focuses on the "what" and "why" rather than the "how"

Provide ONLY the commit message itself, without any additional text, explanations, or formatting.

Code changes:

I have used it in my bash script ci and it works very well! ...

Set Up a 2GB Swap on a Remote VPS with a Simple Script

Running a small VPS with limited memory can be frustrating, especially when processes get killed due to low memory. A quick and easy way to help prevent this is by setting up a swap file.

This script will

  1. Checks if swap already exists on the remote machine.
  2. If not, it creates a 2GB swap file and enables it.
  3. Adds the swap file to /etc/fstab to make it permanent.

The script uses scp to copy a temporary script to the remote machine and ssh to execute it. Here’s the full script:

#!/bin/bash

# Check if machine name is provided
if [ -z "$1" ]; then
  echo "Usage: $0 <machine-name>"
  exit 1
fi

REMOTE_MACHINE=$1
SWAPFILE=/swapfile
SIZE=2048

# Generate remote script content
REMOTE_SCRIPT=$(cat <<EOF
#!/bin/bash
if swapon --show | grep -q "$SWAPFILE"; then
  echo "Swap is already enabled on $SWAPFILE"
  exit 0
fi

sudo dd if=/dev/zero of=$SWAPFILE bs=1M count=$SIZE
sudo chmod 600 $SWAPFILE
sudo mkswap $SWAPFILE
sudo swapon $SWAPFILE

if ! grep -q "$SWAPFILE" /etc/fstab; then
  echo "$SWAPFILE none swap sw 0 0" | sudo tee -a /etc/fstab
fi
free -h
EOF
)

# Save remote script locally
echo "$REMOTE_SCRIPT" > /tmp/create_swap.sh

# Copy script to remote machine and execute it
scp /tmp/create_swap.sh $REMOTE_MACHINE:/tmp/
ssh $REMOTE_MACHINE "bash /tmp/create_swap.sh"

# Cleanup
ssh $REMOTE_MACHINE "rm /tmp/create_swap.sh"

How It Works

  • The script checks if the swap file already exists by running swapon --show on the remote machine.
  • If swap is already enabled, it exits.
  • Otherwise, it creates a 2GB swap file (/swapfile), sets the right permissions, and adds it to /etc/fstab so it’s automatically enabled after a reboot.

Usage

  1. Save the script as create_swap.sh and make it executable:

    chmod +x create_swap.sh
    
  2. Run the script with the remote machine name:

    ./create_swap.sh <remote-machine>
    

And that's it! The script takes care of everything for you, ensuring your VPS has a swap file ready to handle memory spikes.

Build command for deploying your flutter web app to cloudflare pages

set -x && if cd flutter; then git pull && cd .. ; else git clone https://github.com/flutter/flutter.git; (cd flutter && git fetch --tags && git checkout 3.22.3); fi && ls && flutter/bin/flutter doctor && flutter/bin/flutter clean && flutter/bin/flutter config --enable-web && cp .env.production .env && sed -i "s/VERSION_PLACEHOLDER/`git rev-parse --short HEAD`/" .env && flutter/bin/flutter build web --web-renderer html --base-href="/" --release

A bash script `ci` to help you write commit message and commit with OPEN AI/Groq API

Writing commit message could be time-consuming if you want a good summrize. ChatGPT just released their cheapest but still powerful model gpt-4o-mini, we can use it to save our time and keep the commit message accurate.

Attention

I refine the following script time by time and keep the latest version on github. Click here to see the latest version!

You need to put your API KEY in environment variable OPENAI_API_KEY before running this script. You need to run git add first before running this ci script. If you don't want to bother adding first, change git diff --cached -w -b to git diff -w -b and add -a option in the commit command (the last line of the script)

#!/bin/bash

# Get git changes
changes=$(git diff --cached -w -b)

# Exit if no changes
if [ -z "$changes" ]; then
  echo "No changes to commit."
  exit 0
fi

# Set prompt template
prompt_template=$(cat <<-END
You are skilled at writing git commit messages and follow the conventional commits specification:

    refactor: for refactoring
    fix: for bug fixes
    minor: for minor changes
    ...

You will be given the changes from a 'git diff -w -b HEAD' command.
Please summarize all meaningful changes into one commit message, no more than 100 characters.
Respond only with the commit message. Do not mention unchanged aspects. Do not put doube quote in the message. Do not escape underscore characters.
DO REVISE THE MESSAGE THREE TIMES before sending it out. And again: no more than 100 characters!!!
Here are the changes:

END
)

prompt_template+="$changes"

# Build JSON request body using jq
request_body=$(jq -n --arg model "gpt-4o-mini-2024-07-18" --arg prompt "$prompt_template" \
  '{model: $model, messages: [{role:"system",content:"You are a programmer"},{role: "user", content: $prompt}], max_tokens: 32768, seed: 45, temperature: 0}')

# Use curl to request the OpenAI API to generate a commit message
response=$(curl -s --request POST \
  --url https://api.openai.com/v1/chat/completions \
  --header "Authorization: Bearer $OPENAI_API_KEY" \
  --header "Content-Type: application/json" \
  --data "$request_body")

# Extract commit message from the response
commit_message=$(echo "$response" | jq -r '.choices[0].message.content')

# Exit if the commit message is empty
if [ -z "$commit_message" ] || [ "$commit_message" == "null" ]; then
  echo 'failed to generate a commit message:'
  echo $response
  exit 1
fi

# Commit changes
git commit -m "$commit_message"
```bash
**2024-07-24 update**
## Free alternative provided by Groq

If you don't want to pay for the ChatGPT API, you can opt for the free alternative provided by [Groq](https://groq.com). To get started, simply sign up for a Groq account using Google Login. Once you've created your account, you can generate an API key by following this link: <https://console.groq.com/keys>. Finally, make a minor modification to your script, as outlined below.

Build JSON request body using jq

#request_body=$(jq -n arg model "gpt-4o-mini-2024-07-18" arg prompt "$prompt_template" \

'{model: $model, messages: [{role:"system",content:"You are a programmer"},{role: "user", content: $prompt}], max_tokens: 50, seed: 45, temperature: 0}')

#response=$(curl -s --request POST \

--url https://api.openai.com/v1/chat/completions \

--header "Authorization: Bearer $OPENAI_API_KEY" \

--header "Content-Type: application/json" \

--data "$request_body")

request_body=$(jq -n arg model "mixtral-8x7b-32768" arg prompt "$prompt_template"
'{model: $model, messages: [{role:"system",content:"You are a programmer"},{role: "user", content: $prompt}], max_tokens: 32768, stream: false, temperature: 0, top_p: 1, stop: null}')

Use curl to request the OpenAI API to generate a commit message

response=$(curl -s request POST
url https://api.groq.com/openai/v1/chat/completions
header "Authorization: Bearer $GROQ_API_KEY"
header "Content-Type: application/json"
--data "$request_body")