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,412
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: 2,001
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: 519

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: 19

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: 19

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 2022-01-24 09:47:08

seth
Member
Registered: 2012-09-03
Posts: 51,055

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 (2022-01-24 09:58:54)

Offline

#3658 2022-02-25 11:00:20

zynex
Member
Registered: 2019-03-20
Posts: 20

Re: Post your handy self made command line utilities

A simple script to check your internal and external IP addresses..

#!/bin/bash

result=$(curl -s http://ip-api.com/json)

local=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')
ip=$(echo $result | jq -r ".query")
city=$(echo $result | jq -r ".city")
country=$(echo $result | jq -r ".country")
region=$(echo $result | jq -r ".regionName")
isp=$(echo $result | jq -r ".isp")

printf "Local IP: $local\n"
printf "Public IP: $ip\n"
printf "Location: $city ($region), $country\n"
printf "ISP: $isp\n"

Sample output:

Local IP: 192.168.0.122
Public IP: 158.174.51.123
Location: Gothenburg (Västra Götaland County), Sweden
ISP: Bahnhof AB

Last edited by zynex (2022-02-25 11:02:14)

Offline

#3659 2022-02-25 12:43:31

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

Re: Post your handy self made command line utilities

Simple function/script to (most likely) shrink PDF files. Uses ghostscript to convert them to 150dpi. There are also more options like 75dpi or 300dpi etc. but I think 150 is fine as a default value. Useful if someone often sends you huge PDFs.

# Shrink PDF files (output will be a 150dpi PDF file)
shrinkpdf() {
  # Check requirements
  for cmd in 'ps2pdf' 'stat' 'numfmt' 'basename' 'head'; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      echo "Error: '$cmd' is required. Please install it first."
      return 1
    fi
  done

  # Check parameters
  if [ ! "$#" -gt 0 ]; then
    echo "Usage: shrinkpdf <PDF Files>";
    return 1
  fi

  # Loop over parameters
  for pdf in "$@"; do
    # Check if it's a PDF file
    if [ "$(head -c 4 "$pdf")" = "%PDF" ]; then
      INPUTPDFSIZE="$(stat -c %s "$pdf" | numfmt --to=iec)"
      OUTPUTPDF="$(echo "$pdf" | sed 's/.*\/.*\.\(.*\)$/\1/')~smaller.pdf"  # <basename>~smaller.pdf

      # Shrink PDF to 150dpi ("ebook" setting of ghostscript)
      if [ ! -e "$OUTPUTPDF" ]; then
        if ps2pdf -dPDFSETTINGS=/ebook "$pdf" "$OUTPUTPDF"; then
          OUTPUTPDFSIZE="$(stat -c %s "$OUTPUTPDF" | numfmt --to=iec)"
          echo "Shrinked $pdf ($INPUTPDFSIZE) to $OUTPUTPDF ($OUTPUTPDFSIZE)"
        else
          echo "An error occured while shrinking $pdf ($INPUTPDFSIZE) to $OUTPUTPDF"
        fi
      else
        echo "Can't write output file because it already exists: $OUTPUTPDF"
        return 1
      fi
    else
      echo "Not a PDF file, skipping: $pdf"
    fi
  done
}

Last edited by m6x (2022-02-25 13:01:59)


int pi = 3;

Offline

#3660 2022-02-25 15:00:40

SweepingBishops
Member
Registered: 2022-02-14
Posts: 30

Re: Post your handy self made command line utilities

Script taken down due to bugs.

Last edited by SweepingBishops (2022-02-25 15:24:04)

Offline

#3661 2022-02-25 15:37:16

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,523
Website

Re: Post your handy self made command line utilities

zynex wrote:

A simple script to check your internal and external IP addresses...

That can be done without all those pipes, and without needing several calls to jq:

#!/bin/sh

ip addr | sed -n '/state UP/{n;n;h;};${g;s/[^0-9]*\([0-9\.]*\).*/Local IP: \1/p;}'

curl -s http://ip-api.com/json | jq -r '
	"Public IP: " + .query,
	"Location: " + .city + " (" + .regionName + "), " + .country,
	"ISP: " + .isp'

"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3662 2022-02-26 03:12:04

Docbroke
Member
From: India
Registered: 2015-06-13
Posts: 1,433

Re: Post your handy self made command line utilities

or

ip addr | sed -n '/state UP/{n;n;h;};${g;s/[^0-9]*\([0-9\.]*\).*/Local IP: \1/p;}'

curl -s https://ipinfo.io  | tr -d '"{}'

Offline

#3663 2022-02-26 13:44:22

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

Re: Post your handy self made command line utilities

Another possibility is to specify ip addr options:

ip addr show scope global up

ip even has JSON output:

ip -4 -j addr show scope global up | jq '.[].addr_info'

Fun smile

Last edited by Alad (2022-02-26 13:45:40)


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

Offline

#3664 2022-03-03 18:54:14

InvisibleRasta
Member
Registered: 2017-04-12
Posts: 111

Re: Post your handy self made command line utilities

The script from post #3611 seems a bit broken. It will exit if there is no orphaned packages: "error: no targets specified (use -h for help)" and skips the rest of the script.
https://bbs.archlinux.org/viewtopic.php … 4#p1994904

Offline

#3665 2022-03-03 21:15:02

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Than move it to an array:

mapfile -t orph < <(sudo pacman -Qdtq)
sudo pacman -Rsn "${orph[@]}"

Should keep the 'rest' of the script running...

edit:although I do get that same message it doesn't stop my script from running!, you could also:

mapfile -t orph < <(sudo pacman -Qdtq)
for o in "${orph[@]}"; do sudo pacman -Rsn "${o}"; done

Last edited by qinohe (2022-03-03 21:38:55)

Offline

#3666 2022-03-03 22:08:57

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,523
Website

Re: Post your handy self made command line utilities

Ah, the array would not address that at all.  You just create and expand an array for no reason - the result is still that pacman is not passed any arguments.  You could redirect the error output if you wanted (but redirecting pacman's output is not wise ... of course in the context of that script, who cares).  But then to prevent the non-zero exit value, just follow it with "||:", for example:

pacman -Rsn $(pacman -Qdtq) 2>/dev/null ||:

"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3667 2022-03-03 22:16:00

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Thanks Trilby, yes that's why I posted the for loop too, but I guess that won't help much either?
Like I saidI didn't say I have tried that specific script, but I'm sure it don't stop at "error: no targets specified (use -h for help)"
I have tested that... though I must say that array I posted is a function!

edit: could you explain a little more why it's not wise to redirect pacman's output?

Oh, now I get what you say; it's not wise to suppress these messages by redirecting them.
I agree, I would not use that in any of my own scripts ... messages are there for a purpose in the first place.

Last edited by qinohe (2022-03-04 01:09:35)

Offline

#3668 2022-03-04 12:01:56

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

Re: Post your handy self made command line utilities

for o in "${orph[@]}"; do sudo pacman -Rsn "${o}"; done

This is most definitely something you want to avoid - calling processes in a loop is one of the best ways to make bash slow. And you might have one prompt per package too, which is not very nice.

Instead of ignoring errors, you can use xargs -r:

pacman -Qdtq | xargs -r pacman -Rsn

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

Offline

#3669 2022-03-04 16:51:54

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Alad wrote:

This is most definitely something you want to avoid - calling processes in a loop is one of the best ways to make bash slow. And you might have one prompt per package too, which is not very nice.

Yes, I already gathered this should happen it was a bad idea I agree!

Instead of ignoring errors, you can use xargs -r:

pacman -Qdtq | xargs -r pacman -Rsn

This is a nice way to solve the problem. Thanks for showing this;-) I already read some 'man xargs'.
I think the longer I use scripting the more 'unfolds' that I didn't know...back to school it is than.

Offline

#3670 2022-03-05 07:18:41

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

I have given this much more thought than it deserves actually.
If you successfully want to remove orphans there's a correct solution already, use the example from the wiki and run it from a terminal:

# pacman -Qtdq | pacman -Rns -

The problem that was presented however was to use this command in a bash script.

@Alad, your command works fine if there are no orphans, but it will fail if there are!
The command will go back to the prompt as if you entered "No"

@Trilby, your command simply hides the problem as if there was none, though, it works fine, like you said; 'in the context of that script, who cares'!

It's just I dislike hiding output;-)

If you want to run this command from a bash! script if there are or aren't any orphans this is a simple solution that wont fail nor does it hide anything.
The removal simply wont run if there are no orphans...

mapfile -t orph < <(pacman -Qdtq)
if (( ${#orph[@]} != 0 )); then
    sudo pacman -Rsn "${orph[@]}"
fi

You can make your own guess about 'sudo'! and enclose the whole thing in a function if you like.

Offline

#3671 2022-03-05 13:29:53

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,523
Website

Re: Post your handy self made command line utilities

You still don't need bashisms like arrays and mapfile for that approach:

orphans=$(pacman -Qdtq)
[ -n "$orphans" ] && pacman -Rsn $orphans

"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3672 2022-03-05 14:17:33

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

Re: Post your handy self made command line utilities

Indeed, it works with word splitting because pkgname can't contain spaces.

@Alad, your command works fine if there are no orphans, but it will fail if there are!

Right, the pacman prompt doesn't play well with stdin. Either use pacman --noconfirm, one of the approaches above, or xargs -a:

xargs -a <(pacman -Qdtq) -r sudo pacman -Rsn

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

Offline

#3673 2022-03-06 17:35:50

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Trilby wrote:

You still don't need bashisms like arrays and mapfile for that approach:

Agreed, I was led astray by multiple packages...)

Alad wrote:

Right, the pacman prompt doesn't play well with stdin.

That's clear now!

Either use pacman --noconfirm, one of the approaches above, or xargs -a:

Nice, I think InvisibleRasta or anyone else;-) can make a pick now!

Offline

#3674 2022-03-07 20:19:16

lenhuppe
Member
From: New Hampshire USA
Registered: 2018-12-10
Posts: 272
Website

Re: Post your handy self made command line utilities

I wanted a way to use the AUR from a series of installation scripts. Further, I wanted the scripts to require sudo access. Lastly I wanted my scripts to provide plenty of feedback as they run for debugging. What I came up with is a hack but it does not require any AUR helper. Here are two examples:

dropbox_setup.sh

#!/usr/bin/env bash

set -e

# language = English
export LANG=C

# print messages
function print {
	tput setaf 2 ; echo -e "\n\t$1\n" ; tput sgr0
}

# dropbox package list
dbox_pkgs=( dropbox dropbox-cli nautilus-dropbox )

# verify userid
[ "$(id -u)" != 0 ] && print "Run this script with sudo" && exit 1

print "Installing Dropbox"

# key
print "Importing Dropbox key"
sudo -u "$SUDO_USER" bash << _eof_
curl -L https://linux.dropbox.com/fedora/rpm-public-key.asc | gpg --import -
_eof_

# aur
for p in "${dbox_pkgs[@]}"; do
print "Building $p"
sudo -u "$SUDO_USER" bash << _eof_
cd /tmp ; git clone https://aur.archlinux.org/"$p"
cd "$p" ; makepkg --noconfirm -sic
_eof_
done

print "Dropbox setup complete"

   

This method worked well when I needed to apply two patches in order to setup my Epson scanner:

iscan_setup.sh

#!/usr/bin/env bash

set -e

# language = English
export LANG=C

# print messages
function print {
	tput setaf 2 ; echo -e "\n\t$1\n" ; tput sgr0
}

# verify userid
[ "$(id -u)" != 0 ] && print "Run this script with sudo" && exit 1

print "Installing Iscan"

sudo -u "$SUDO_USER" bash << _eof_

# build libstdc++5-bin since libstdc++5 is broken
cd /tmp ; git clone https://aur.archlinux.org/libstdc++5-bin
cd libstdc++5-bin ; makepkg --noconfirm -sic

# build iscan with libstdc++5-bin
cd /tmp ; git clone https://aur.archlinux.org/iscan
sed -i "s/depends=('gtk2' 'sane' 'libstdc++5')/depends=('gtk2' 'sane' 'libstdc++5-bin')/" /tmp/iscan/PKGBUILD
cd iscan ; makepkg --noconfirm -sic

# build iscan-data
cd /tmp ; git clone https://aur.archlinux.org/iscan-data
cd iscan-data ; makepkg --noconfirm -sic

# build iscan iscan-plugin-perfection-v370
cd /tmp ; git clone https://aur.archlinux.org/iscan-plugin-perfection-v370
cd iscan-plugin-perfection-v370 ; updpkgsums && makepkg --noconfirm -sic

_eof_

print "Iscan setup complete"

Last edited by lenhuppe (2022-03-07 20:21:45)


Why do we drive on the parkway and then park in the driveway?

Offline

#3675 2022-03-07 23:48:11

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Or get 'any' package you want and get on building it the way you like, my get part:

url='https://aur.archlinux.org/cgit/aur.git/snapshot/'      
buildir="$HOME"/build
prog=$2

_get() {
  [ -d "$buildir/$prog" ] && mv "$buildir/$prog" "$buildir/${prog}.bak"

  curl -sL "${url}${prog}.tar.gz" -o "$buildir/${prog}.tar.gz"

  tar zxvf "$buildir/${prog}.tar.gz" -C "$buildir" #&& rm "$buildir/${prog}.tar.gz"

}
_get "$@"

I mean your two scripts are for one package each, which you could make into 'one rules them all';-) mostly that is!

Offline

Board footer

Powered by FluxBB