You are not logged in.

#3826 2025-08-14 14:15:13

Succulent of your garden
Member
From: Majestic kingdom of pot plants
Registered: 2024-02-29
Posts: 1,101

Re: Post your handy self made command line utilities

Probably some here know this but I'm going to put this for those who maybe doesn't know yet, it uses this https://github.com/chubin/wttr.in :

#!/bin/sh
choice=$(echo "" | dmenu -p 'Please write city to check weather: ')
link="wttr.in/$choice"
kitty --hold -- bash -c "curl $link; read -p 'Press Enter to exit'"

I use it with a keybinding to launch it quickly without the terminal and check the weather where I lived. Obviously you can check the weather in anywhere of the world. most of the time have a decent accuracy of the weather. It's a very short and minimal script but it's very useful to me. I use dmenu to insert the city and kitty. The kitty usage is just because of the graphics capabilities since is not my default terminal, but you can use it in any terminal you want with some tweaks. So if someone have a different setup like for example rofi, it could be nice to see the variation of this script here. 

When I'm in a hurry and I need to get outside fast, this scripts makes my day, since I no longer need to go to accuweather to check the weather smile

Last edited by Succulent of your garden (2025-08-14 14:17:53)


str( @soyg ) == str( @potplant ) btw!

Offline

#3827 2025-09-03 17:50:00

karabaja4
Member
From: Croatia
Registered: 2008-09-14
Posts: 1,032
Website

Re: Post your handy self made command line utilities

Small python script that renders a black rectangle window that can be maximized with right click and closed with left click. Use -m to start it in fullscreen. I use it as an OLED screensaver for my laptop while working on an external monitor.

Requires tk package installed.

#!/usr/bin/env python3
import sys
import os
import tkinter as tk

class ToggleFullscreenApp:
    def __init__(self, root, start_fullscreen=False):
        self.root = root
        self.fullscreen = False

        # Initial window size (rectangle)
        self.width = 1280
        self.height = 800
        self.root.geometry(f"{self.width}x{self.height}")  # let WM place it
        self.root.configure(background="black")
        
        pid = os.getpid()
        self.root.title(f"OLED saver [{pid}]")

        # Bind click events
        self.root.bind("<Button-3>", self.toggle_fullscreen)
        self.root.bind("<Button-1>", self.exit_app)

        # Force window manager to place window and get actual geometry
        self.root.update_idletasks()
        x = self.root.winfo_x()
        y = self.root.winfo_y()
        w = self.root.winfo_width()
        h = self.root.winfo_height()
        self.saved_geometry = f"{w}x{h}+{x}+{y}"

        # Start in fullscreen if requested
        if start_fullscreen:
            self.toggle_fullscreen()

    def toggle_fullscreen(self, event=None):
        self.fullscreen = not self.fullscreen
        if self.fullscreen:
            # Save current geometry
            self.root.update_idletasks()
            x = self.root.winfo_x()
            y = self.root.winfo_y()
            w = self.root.winfo_width()
            h = self.root.winfo_height()
            self.saved_geometry = f"{w}x{h}+{x}+{y}"

            # Go fullscreen
            self.root.attributes("-fullscreen", True)
        else:
            # Restore original size and position
            self.root.attributes("-fullscreen", False)
            self.root.geometry(self.saved_geometry)

    def exit_app(self, event=None):
        self.root.quit()


if __name__ == "__main__":
    script_name = sys.argv[0]
    
    if "-h" in sys.argv or "--help" in sys.argv:
        print(
            f"Usage: python3 {script_name} [options]\n\n"
            "Options:\n"
            "  -h, --help      Show this help message and exit\n"
            "  -m              Start the application in fullscreen mode\n\n"
            "Controls:\n"
            "  Right-click     Toggle fullscreen on/off\n"
            "  Left-click      Exit the application"
        )
        sys.exit(0)
    
    start_fullscreen = "-m" in sys.argv
    root = tk.Tk()
    app = ToggleFullscreenApp(root, start_fullscreen=start_fullscreen)
    root.mainloop()

Last edited by karabaja4 (2025-09-11 22:05:52)

Offline

#3828 2025-11-28 01:22:53

teckk
Member
Registered: 2013-02-21
Posts: 562

Re: Post your handy self made command line utilities

If you already have qt6-webengine installed,

Here is a little web page to pdf cpp file, with user agent, script, image, font, paper size/margins adjustments. Good for calling from a bash script, or with args.

html2pdf.cpp

// Web page to pdf
// Needs qt6-base, qt6-webengine

#include <QApplication>
#include <QCommandLineParser>
#include <QFile>
#include <QTextStream>
#include <QWebEngineView>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QMarginsF>
#include <QPageLayout>
#include <QPageSize>

#include <functional>
#include <utility>

//User Agent iphone18 Chrome 141
const char* AgentIphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_6_2 "
    "like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) "
    "CriOS/141.0.73393.39 Mobile/15E148 Safari/604.1";

//User Agent Win10 firefox 143
const char* AgentWin10 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; "
    "rv:143.0) Gecko/20100101 Firefox/143.0";

/*** Set User Agent, Scripts, Images, Font Size, Paper size here ***/
//Set User agent
const char* agent = AgentIphone;

//Set javascript and images on/off, font size
const bool js = false;
const bool im = true;
const int fs = 18;

//Paper sizes
//Letter 216×279, Legal 216×356, Ledger 279×432, Tabloid 432×279
//A4 210x297, A3 297x420, A2 420x594, A1 594x841

//Set Paper size, margins
const QPageLayout layout(
    //QPageSize(QPageSize::Letter), QPageLayout::Portrait,
    //QPageSize(QPageSize::Ledger), QPageLayout::Portrait,
    QPageSize(QPageSize::Tabloid), QPageLayout::Portrait,
    QMarginsF(0, 2, 0, 2), //(left, top, right, bottom)
    QPageLayout::Millimeter
);
/************************* End of Settings *************************/

class Html2PdfConverter : public QObject {
    Q_OBJECT
public:
    explicit Html2PdfConverter(QString inputPath, QString outputPath);
    int run();

private slots:
    void loadFinished(bool ok);
    void pdfPrintingFinished(const QString &filePath, bool success);

private:
    QString m_inputPath;
    QString m_outputPath;
    QScopedPointer<QWebEngineView> m_view;
};

Html2PdfConverter::Html2PdfConverter(QString inputPath, QString outputPath)
    : m_inputPath(std::move(inputPath))
    , m_outputPath(std::move(outputPath))
    , m_view(new QWebEngineView) {
    connect(m_view.data(), &QWebEngineView::loadFinished,
            this, &Html2PdfConverter::loadFinished);
    connect(m_view.data(), &QWebEngineView::pdfPrintingFinished,
            this, &Html2PdfConverter::pdfPrintingFinished);
}

int Html2PdfConverter::run() {
    m_view->load(QUrl::fromUserInput(m_inputPath));
    return QApplication::exec();
}

void Html2PdfConverter::loadFinished(bool ok) {
    if (!ok) {
        QTextStream(stderr)
            << tr("failed to load URL '%1'").arg(m_inputPath) << "\n";
        QCoreApplication::exit(1);
        return;
    }

    m_view->printToPdf(m_outputPath, layout);
}

void Html2PdfConverter::pdfPrintingFinished(const QString &filePath, bool success) {
    if (!success) {
        QTextStream(stderr)
            << tr("failed to print to output file '%1'").arg(filePath) << "\n";
        QCoreApplication::exit(1);
    } else {
        QCoreApplication::quit();
    }
}

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    QCoreApplication::setOrganizationName("web2pdf6");
    QCoreApplication::setApplicationName("html2pdf6");
    QCoreApplication::setApplicationVersion(QT_VERSION_STR);
    
    QWebEngineProfile::defaultProfile()->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, js);
    QWebEngineProfile::defaultProfile()->settings()->setAttribute(QWebEngineSettings::AutoLoadImages, im);
    QWebEngineProfile::defaultProfile()->settings()->setFontSize(QWebEngineSettings::DefaultFontSize, fs);
    QWebEngineProfile::defaultProfile()->settings()->setFontFamily(QWebEngineSettings::StandardFont, "monospace");
    QWebEngineProfile::defaultProfile()->setHttpUserAgent(agent);

    QCommandLineParser parser;
    parser.setApplicationDescription(
        QCoreApplication::translate("main", "Converts the web page INPUT into the PDF file OUTPUT."));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument(
        QCoreApplication::translate("main", "INPUT"),
        QCoreApplication::translate("main", "Input URL for PDF conversion."));
    parser.addPositionalArgument(
        QCoreApplication::translate("main", "OUTPUT"),
        QCoreApplication::translate("main", "Output file name for PDF conversion."));

    parser.process(QCoreApplication::arguments());

    const QStringList requiredArguments = parser.positionalArguments();
    if (requiredArguments.size() != 2)
        parser.showHelp(1);

    Html2PdfConverter converter(requiredArguments.at(0), requiredArguments.at(1));
    return converter.run();
}

#include "html2pdf.moc"

html2pdf.pro

TEMPLATE = app

QT += webenginewidgets

SOURCES += html2pdf.cpp

target.path = $$[QT_INSTALL_EXAMPLES]/webenginewidgets/html2pdf
INSTALLS += target

Offline

#3829 2025-12-06 19:24:36

EISENFELD
Member
From: Germany
Registered: 2024-03-13
Posts: 41
Website

Re: Post your handy self made command line utilities

Small Bash / Python script to get the system age: (works only with ext2/3/4 root fs so far)
If you like ,you can easily extend fastfetch with this script by using the "command" module to execute script.

#!/bin/bash

# 1. Find the root partition device (e.g., /dev/sda2)
ROOT_DEV=$(findmnt -n -o SOURCE /)

# 2. Extract the filesystem creation date using tune2fs
# Using sudo as tune2fs -l requires root permissions
# The grep/cut/xargs part extracts the raw date-time string
INSTALL_DATE_STRING=$(sudo tune2fs -l "$ROOT_DEV" 2>/dev/null | grep 'Filesystem created:' | cut -d: -f 2- | xargs)

# 3. Process the date in Python and calculate the difference
# (Note: tune2fs only works reliably for ext2/3/4)

python3 -c "
from datetime import datetime, date
import locale
# Set locale to 'C' to ensure consistent date parsing regardless of system language (e.g., 'Mar' vs 'Mär')
try:
    locale.setlocale(locale.LC_ALL, 'C')
    
    # Parsing date format like 'Sat Mar 16 14:30:22 2024'
    creation_datetime = datetime.strptime('$INSTALL_DATE_STRING', '%a %b %d %H:%M:%S %Y')
    d1 = creation_datetime.date()
    d2 = date.today()
    print(f'Installation: {d1}, {(d2-d1).days} days old.\n')
except ValueError:
    print('❌ ERROR: Could not extract creation date from tune2fs.')
    print('This usually happens if the filesystem does not store a creation time (e.g., XFS or Btrfs).')
    print('Please use the manual method (Pacman Logs) for non-ext filesystems.\n')
"

Ich weiß, dass ich nichts weiß !

Offline

#3830 2025-12-06 19:42:04

schard
Forum Moderator
From: Hannover
Registered: 2016-05-06
Posts: 2,462
Website

Re: Post your handy self made command line utilities

LANG=C stat / | grep -i birth

Inofficial first vice president of the Rust Evangelism Strike Force

Offline

#3831 2025-12-06 20:03:10

seth
Member
From: Don't DM me only for attention
Registered: 2012-09-03
Posts: 71,055

Re: Post your handy self made command line utilities

stat -c %w /

Offline

#3832 2025-12-07 03:18:56

EISENFELD
Member
From: Germany
Registered: 2024-03-13
Posts: 41
Website

Re: Post your handy self made command line utilities

Thank you very much! Now this is a much better version to get the days since installation.

#!/bin/bash

# 1. Retrieve the birth time of the root filesystem.
# stat -c %w / outputs the creation date of the '/' directory.
# Example output: 2024-03-16 14:30:22.000000000 +0100
INSTALL_DATE_FULL=$(stat -c %w /)

# Important check: If %w is not supported (e.g., older kernels/FS),
# stat returns the string "n/a". We check this before calculating.
if [[ "$INSTALL_DATE_FULL" == "n/a" ]]; then
    echo "❌ ERROR: Birth time (%w) is not supported by the filesystem."
    echo "➡️ Please use the Pacman Log method as a fallback."
    exit 1
fi

# 2. Convert the full date string (including timestamp and timezone) to seconds since epoch.
# GNU date is robust enough to handle the full stat output.
INSTALL_DATE_SECONDS=$(date -d "$INSTALL_DATE_FULL" +%s)
CURRENT_DATE_SECONDS=$(date +%s)

# 3. Calculate the difference in days (86400 seconds per day).
DAYS=$(( ($CURRENT_DATE_SECONDS - $INSTALL_DATE_SECONDS) / 86400 ))

# 4. Clean output for Fastfetch
echo "System installed for $DAYS days."

Ich weiß, dass ich nichts weiß !

Offline

#3833 2025-12-07 13:16:58

snakeroot
Member
Registered: 2012-10-06
Posts: 175

Re: Post your handy self made command line utilities

What about this:

echo "System installed for $(( ($(date +%s) - $(stat -c %W / )) / 86400 )) full days"

Offline

#3834 2025-12-07 19:12:52

256
Member
Registered: 2023-12-17
Posts: 59

Re: Post your handy self made command line utilities

EISENFELD wrote:
# Important check: If %w is not supported (e.g., older kernels/FS),
# stat returns the string "n/a". We check this before calculating.

Is that true? If I try %w on something that I assume doesn't support it, like /proc, it gives "-". Does it produce "n/a" on other filesystems?


"Don't comment bad code - rewrite it." - The Elements of Programming Style (1978), Brian W. Kernighan & P. J. Plauger, p. 144.

Offline

#3835 2025-12-07 19:19:38

ReDress
Member
From: Nairobi
Registered: 2024-11-30
Posts: 163

Re: Post your handy self made command line utilities

Userspace.

Can I please be kernel space.

WORK harder

Offline

Board footer

Powered by FluxBB