You are not logged in.

#3651 2021-12-08 18:53:47

Alad
Wiki Admin/IRC Op
From: Bagelstan
Registered: 2014-05-04
Posts: 2,252
Website

Re: Post your handy self made command line utilities

I also have 2 more aliases for the AUR using "paru -a". I like keeping the AUR operations separate.

If you like to keep AUR operations separate (which makes sense), why use a pacman wrapper?


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby

Offline

#3652 2021-12-19 17:44:36

Dieter@be
Forum Fellow
From: Belgium
Registered: 2006-11-05
Posts: 1,988
Website

Re: Post your handy self made command line utilities

I've built a shell script which tests how your terminal font looks like in various styles (normal, bold, italic, underline, etc) and also tests display of icons and emoji's
edit: it looks like some of the emoji don't make it through the bbs submit form, you can also find the script here: https://gist.github.com/Dieterbe/91559a … 5ece23075d

#!/bin/bash

read -r -d '' text <<'EOF'
'" <> ?+| /=\ -_ ,.:;
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
! @ # $ % ^ & * ( ) { }
1 2 3 4 5 6 7 8 9 0 [ ]
EOF
echo -e "Regular:\n$text"
echo -e "\n\e[1mBold:\n$text\e[0m"
echo -e "\n\e[3mItalic:\n$text\e[0m"
echo -e "\n\e[3m\e[1mBold italic:\n$text\e[0m"
echo -e "\n\e[4mUnderline:\n$text\e[0m"
echo -e "\n\e[9mStrikethrough:\n$text\e[0m"
echo
echo "Icons:"
echo "FontAwesome       MaterialDesign    Devicons             Octicons       Powerline                        Seti-Ui           Weather-icons"
echo " nf-fa-wifi      直nf-mdi-wifi      nf-dev-gulp         nf-oct-x      nf-ple-flame_thick              nf-seti-xml      nf-weather-sleet"
echo " nf-fa-arrow_up   nf-mdi-battery   nv-def-hackernews   nf-oct-star   nf-ple-honeycomb                nf-seti-folder   nf-weather-meteor"
echo " nf-fa-battery    nf-mdi-apple     nf-dev-github       nf-oct-key    nf-ple-left_half_circle_thick   nf-seti-python   nf-weather-alien"
echo
echo "Icon size comparison examples"
echo "see https://github.com/ryanoasis/nerd-fonts/issues/127"
echo -e "Small?:\uf300\uf460\ue70a\ue258"
echo -e "So-so?:\uf000\uf072"
echo -e "Normal:\ue285\uf245"
echo
echo "Emoji (not part of nerdfonts):"
echo "Smileys/people  ? U+1f600 Grinning face        ? U+1F648 See-no-evil Monkey"
echo "Animals/Nature  ? U+1F43E Paw Prints           ? U+1F332 Evergreen Tree"
echo "Food/Drink      ? U+1F32D Hot Dog              ? U+1F942 Clinking Glasses"
echo "Activities      ? U+1F3B4 Flower Playing Cards ? U+1F94C <no description>"
echo "Travel/Places   ? U+1F525 Fire                 ? U+1F304 Sunrise Over Mountains"
echo "Objects         ? U+1F3A4 Microphone           ? U+1F941 Drum With Drumsticks"
echo "Symbols         ? U+1F193 Squared Free         ? U+1F6D0 Place Of Worship "
echo "Flags           ? U+1F38C Crossed Flags        ? U+1F3F4 Waving Black Flag"

Last edited by Dieter@be (2021-12-19 19:01:05)


< Daenyth> and he works prolifically
4 8 15 16 23 42

Offline

#3653 2021-12-20 14:03:10

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

Re: Post your handy self made command line utilities

This thread is titled programming and scripting. So, not just for scripts.

If anyone is interested, can use this, or build upon it, I developed a command line web inspector that uses Qt5Webengine at it's heart. It prints to terminal and logfile all web page requests in sequential order. It prints request Method, resource Type, and request Url, colorized for Resource Type. It does what the web inspector in a web browser does, except I think it presents the info in a more coherent format. I did not put it in the AUR. Didn't know if anyone cared one way or the other. Plus I am a beginner C++ programmer.

I use this several times a week. I used a python version of this for years. This last year I decided that it was time to start learning c and c++.

I've got several version of this. Here is a small compact 1 file version with everything hard coded.

Obligatory pics in action. Runs in terminal, and gives a small web browser window to "click" on things.
https://0x0.st/-3il.png https://0x0.st/-3iU.png https://0x0.st/-3i0.png
https://0x0.st/-3iG.png https://0x0.st/-3iD.png https://0x0.st/-3ik.png

You'll need g++, qt5 and qt5 webengine, to build it.
At this moment I have installed on this arch machine
gcc gcc-libs qt5-base qt5-declarative qt5-location qt5-multimedia qt5-sensors qt5-svg qt5-webchannel qt5-webengine

inspector.cpp

//Print to terminal and logfile all web page requests in sequential order.
//Print request Method, resource Type, and request Url, colorized.

#include <QApplication>
#include <QCommandLineParser>
#include <QWebEnginePage>
#include <QWebEngineProfile>
#include <QWebEngineUrlRequestInterceptor>
#include <QWebEngineView>
#include <iostream>
#include <fstream>

/**Output Color definitions**/
#define RESET "\033[0m"
#define BOLD  "\033[1m"
#define FGBLK "\033[30m"
#define FGRED "\033[31m"
#define FGGRN "\033[32m" 
#define FGYEL "\033[33m"
#define FGBLU "\033[34m"
#define FGMAG "\033[35m"
#define FGCYA "\033[36m"
#define FGWHI "\033[37m"

#define BGBLK "\033[40m"
#define BGRED "\033[41m"
#define BGGRN "\033[42m"
#define BGYEL "\033[43m"
#define BGBLU "\033[44m"
#define BGMAG "\033[45m"
#define BGCYA "\033[46m"
#define BGWHI "\033[47m"

/**User agents to use**/
//User Agent iphone15 safari
const char* AgentIphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0_1 "
    "like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) "
    "GSA/78.0.257670029 Mobile/19A348 Safari/604.1";
    
//User Agent Win10 firefox
const char* AgentWin10 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; "
    "rv:92.0) Gecko/20100101 Firefox/92.0'";
    
//User Agent Arch firefox
const char* AgentArch = "Mozilla/5.0 (X11; Arch; Linux x86_64; rv:90.0) "
    "Gecko/20100101 Firefox/90.0";

/**App Settings**/
//User agent to use
const char* Agent = AgentIphone;

//Log file
const char* AppLog = "insp.log";

//Colors
const char* BG;
const char* FG;

/**Interceptor class**/
//Intercept requests, print to term and logfile
class UrlRequestInterceptor : public QWebEngineUrlRequestInterceptor
{
    public:
    virtual void interceptRequest(QWebEngineUrlRequestInfo &info)
    {
        QString req = "";
        //Resource type, color for type
        switch(info.resourceType())
        {
            case 0:
                req = "ResourceTypeMainFrame, (Top level page)";
                FG = FGBLK; BG = BGWHI;
                break;
            case 1:
                req = "ResourceTypeSubFrame, (Frame or iframe)";
                FG = FGCYA; BG = BGBLK;
                break;
            case 2:
                req = "ResourceTypeStylesheet, (CSS stylesheet)";
                FG = FGBLK; BG = BGGRN;
                break;
            case 3:
                req = "ResourceTypeScript, (External script)";
                FG = FGWHI; BG = BGRED;
                break;
            case 4:
                req = "ResourceTypeImage, (Image - jpg/gif/png/etc)";
                FG = FGBLK; BG = BGYEL;
                break;
            case 5:
                req = "ResourceTypeFontResource, (Font)";
                FG = FGBLK; BG = BGCYA;
                break;
            case 6:
                req = "ResourceTypeSubResource, (Other subresource)";
                break;
            case 7:
                req = "ResourceTypeObject, "
                    "(Object (or embed) tag for a plugin)";
                FG = FGMAG; BG = BGBLK;
                break;
            case 8:
                req = "ResourceTypeMedia, (Media resource)";
                FG = FGWHI; BG = BGBLU;
                break;
            case 9:
                req = "ResourceTypeWorker, "
                    "(Main resource of a dedicated worker)";
                break;
            case 10:
                req = "ResourceTypeSharedWorker, "
                    "(Main resource of a shared worker)";
                break;
            case 11:
                req = "ResourceTypePrefetch, (Explicitly requested prefetch)";
                break;
            case 12:
                req = "ResourceTypeFavicon, (Favicon)";
                FG = FGYEL; BG = BGBLK;
                break;
            case 13:
                req = "ResourceTypeXhr, (XMLHttpRequest)";
                FG = FGWHI; BG = BGMAG;
                break;
            case 14:
                req = "ResourceTypePing, (Ping request)";
                FG = FGMAG; BG = BGBLK;
                break;
            case 15:
                req = "ResourceTypeServiceWorker, "
                    "(Main resource of a service worker)";
                break;
            case 16:
                req = "ResourceTypeCspReport, "
                    "(Content Security Policy violations)";
                break;
            case 17:
                req = "ResourceTypePluginResource, "
                    "(Resource requested by a plugin)";
                break;
            case 19:
                req = "ResourceTypeNavigationPreloadMainFrame, "
                    "(Vice worker navigation preload request)";
                break;
            default: 
                req = "(Unknown type)";
                break;
        }
        //Print to terminal, logfile
        std::ofstream logFile;
        logFile.open(AppLog, std::ios_base::app);
        
        QString reqUrl = info.requestUrl().toString();
        QString reqMethod = info.requestMethod();
        
        //Colorize output
        std::cout << reqMethod.toStdString() << std::endl
                << FG << BG << req.toStdString() << RESET << std::endl
                << reqUrl.toStdString() << std::endl
                << std::string(70, '_') << std::endl;

        //Append to logfile
        logFile << reqMethod.toStdString() << std::endl 
                << req.toStdString() << std::endl
                << reqUrl.toStdString() << std::endl
                << std::string(70, '_') << std::endl;
        
        logFile.close();
    }
};

/**Constructor**/
void UrlRequestInterceptor::QWebEngineUrlRequestInterceptor::
    interceptRequest(QWebEngineUrlRequestInfo &info)
{
    info.requestUrl();
}

/**Create app, configure, get args**/
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QWebEngineProfile *profile = new QWebEngineProfile();
    profile->setHttpUserAgent(Agent);
    
    QWebEngineUrlRequestInterceptor *interceptor = new UrlRequestInterceptor();
    profile->setUrlRequestInterceptor(interceptor);
    
    QWebEngineView *view = new QWebEngineView;
    QWebEnginePage *page = new QWebEnginePage(profile, view);
    
    //Positional Arguments
    QCommandLineParser cLineParser;
    cLineParser.addPositionalArgument(QStringLiteral("Url"), 
        QStringLiteral()); 
    cLineParser.process(app);
    QStringList posArgs = cLineParser.positionalArguments();
    QUrl url;
    
    //Get args, print error, or prompt
    if (posArgs.size() > 1)         //Too many args
    {
        std::cout << "Too many arguments!" << std::endl;
        return 0;
    } 
    else if (posArgs.size() == 1)   //Open with url arg
    {
        url = QUrl::fromUserInput(posArgs.at(0));
        page->setUrl(QUrl(url));
    } 
    else                            //Prompt for input
    {
        std::string url;
        std::cout << "Enter Paste url to inspect: ";
        std::cin >> url;
        page->setUrl(QString::fromStdString(url));
    }
    
    std::cout << "\n" << "Logfile is: " << AppLog << "\n\n";
    
    page->setZoomFactor(1.4);       //Zoom
    view->setPage(page);
    view->setMinimumSize(1000,800); //Browser size
    view->show();                   //Show browser
        
    return app.exec();
}

inspector.pro

TEMPLATE = app
TARGET = inspector
QT += webenginewidgets

HEADERS += \

SOURCES += \
    inspector.cpp \

FORMS += \

RESOURCES +=

# install
target.path = /path/inspector
INSTALLS += target

Offline

#3654 2021-12-23 02:28:28

Slips
Member
Registered: 2021-12-23
Posts: 4

Re: Post your handy self made command line utilities

I've been working on a pretty basic status reader for Clementine Music Player that just gets a bit of metadata over DBus and prints it.

#!/bin/sh

case $(dbus-send --session --type=method_call --print-reply --dest=org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:'org.mpris.MediaPlayer2.Player' string:'Metadata' 2>&1) in
        "Error org.freedesktop.DBus.Error.ServiceUnknown: The name org.mpris.MediaPlayer2.clementine was not provided by any .service files")
                echo "dbus service not found. Is Clementine running?"
                exit 1
                ;;
	'Failed to open connection to "session" message bus: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11')
		echo "dbus-daemon failed to launch because of missing \$DISPLAY. Is Xorg running?"
		exit 1
		;;
        *)
                break
                ;;
esac

# Finds what line the xesam:artist dbus element is on and adds two to it:
getXesamArtistLine () {
	rawNum=$(dbus-send --session --type=method_call --print-reply --dest=org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:'org.mpris.MediaPlayer2.Player' string:'Metadata' | grep -n xesam:artist | cut -f1 -d:)
	echo "$((rawNum + 2))"
}

# Finds what line the xesam:title dbus element is on and adds one to it:
getXesamTitleLine () {
        rawNum=$(dbus-send --session --type=method_call --print-reply --dest=org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:'org.mpris.MediaPlayer2.Player' string:'Metadata' | grep -n xesam:title | cut -f1 -d:)
        echo "$((rawNum + 1))"
}

#Prints the full dbus Metadata string and then does some Unix Text Parse Magic TM To crop it down to the Artist
getArtist () {
        dbus-send --session --type=method_call --print-reply --dest=org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:'org.mpris.MediaPlayer2.Player' string:'Metadata' | awk -v var=$(getXesamArtistLine) '/string/ {ORS=" "} {if(NR==var){for(i=2;i<=NF;i++) print $i}}' |sed 's/\"//g'
}

#Likewise, but for the title.
getTitle () {
	dbus-send --session --type=method_call --print-reply --dest=org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:'org.mpris.MediaPlayer2.Player' string:'Metadata' | awk -v var=$(getXesamTitleLine) '/string/ {ORS=" "} {if(NR==var){for(i=3;i<=NF;i++) print $i}}' |sed 's/\"//g'
}

#Prints the full dbus PlaybackStatus string and then crops it down to the part we want.
getPlaybackStatus () {
	dbus-send --session --type=method_call --print-reply --dest=org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:'org.mpris.MediaPlayer2.Player' string:"PlaybackStatus" | awk '{if(NR==2)print $3} ' | sed 's/\"//g'
}

getFullStatus () {
	case $(getPlaybackStatus) in
        'Paused')
                echo "$(getArtist)- $(getTitle)($(getPlaybackStatus))"
                break
                ;;
        'Playing')
                echo "$(getArtist)- $(getTitle)"
                break
                ;;
        'Stopped')
                echo "Nothing Playing"
                break
                ;;
esac
}
case $1 in
	-p|--playing)
		echo $(getPlaybackStatus)
		break
		;;
	-a|--artist)
		echo $(getArtist)
		break
		;;
	-t|--title)
		echo $(getTitle)
		break
		;;
	-h|--help)
		echo "ClementEYEne: A simple bash script that gets Clementine Music Player status over dbus"
		echo "------"
		echo "-p, --playing     Get current playback status"
		echo "-a, --artist      Get current track's artist"
		echo "-t, --title       Get current track's title"
		echo "-h, --help        Displays this message."
		echo "No flags will output the full string in <ARTIST> - <TITLE> format. Only one flag at a time can be parsed."
		echo "------"
		break
		;;
		'')
		echo $(getFullStatus)
		break
		;;
		*)
		echo "Usage: clementeyene [OPTION]"
		echo "Try 'clementeyene -h' for more information."
		break
		;;
esac

What's the worst that could happen, rapid brain death?

Offline

#3655 2021-12-24 09:34:48

m6x
Member
From: Germany
Registered: 2020-04-01
Posts: 18

Re: Post your handy self made command line utilities

Alad wrote:

I also have 2 more aliases for the AUR using "paru -a". I like keeping the AUR operations separate.

If you like to keep AUR operations separate (which makes sense), why use a pacman wrapper?

I just like paru, especially the diff-based review of PKGBUILDs.
Which tool did you have in mind instead? Don't mind checking out other options as well.


int pi = 3;

Offline

#3656 2021-12-24 09:37:07

m6x
Member
From: Germany
Registered: 2020-04-01
Posts: 18

Re: Post your handy self made command line utilities

Trilby wrote:

M6x, fyi, your script in post #3601 could just be the following:

#!/bin/sh

lsblk -ndo PATH,MODEL,SERIAL /dev/block/*\:0
printf \\n
lsblk -o NAME,FSTYPE,SIZE,FSAVAIL,TYPE,HOTPLUG,MOUNTPOINT

I originally had it similarly short, but the first line doesn't show info about connected USB drives. So I went the long spaghetti route.

Last edited by m6x (2021-12-24 09:40:50)


int pi = 3;

Offline

#3657 Yesterday 09:47:08

seth
Member
Registered: 2012-09-03
Posts: 26,570

Re: Post your handy self made command line utilities

wget/linode speedtest for reference

#!/bin/bash
locations=("newark" "singapore" "london" "frankfurt" "dallas" "toronto1" "syd1" "atlanta" "tokyo2" "mumbai1" "fremont")
sizes=("100MB" "1GB")
printf " 1. Newark, USA\n 2. Singapore\n 3. London, UK\n 4. Frankfurt, Deutschland\n\
 5. Dallas, USA\n 6. Toronto, Canada\n 7. Sidney, Australia\n 8. Atlanta, USA\n\
 9. 東京都 (Tokyo), 日本国 (Japan)\n10. मुंबई (Bombay), Bhārat (India)\n11. Fremont, USA\n"
read -p "Enter location: " location
location=${locations[location-1]}
printf " 1. 100MB\n 2. 1GB\n"
read -n 1 -p "Slect size: " size
size=${sizes[size-1]}
echo
wget -nv --show-progress -O /dev/null http://speedtest.${location}.linode.com/${size}-${location}.bin

Last edited by seth (Yesterday 09:58:54)

Offline

Board footer

Powered by FluxBB