You are not logged in.

#2751 2016-05-01 22:49:54

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 26,198
Website

Re: Post your handy self made command line utilities

Thanks Earnestly.

The globs hint is a good one, as is the RHS quoting requirement.

The unnecessary quoting is as much habit as it is defensiveness.

Cheers!


Arch + dwm   •   Mercurial repos  •   Github

Registered Linux User #482438

Online

#2752 2016-05-02 02:14:54

Earnestly
Member
Registered: 2011-08-18
Posts: 805

Re: Post your handy self made command line utilities

Yeah, the whole situation of the IFS containing literally every valid file name character is a huge pain in the butt.  There's nothing even stopping you from seeing BS or even, ironically, FS in the name so long as you don't include NUL or '/'.  Yay...

Offline

#2753 2016-05-02 14:27:49

drcouzelis
Member
From: Connecticut, USA
Registered: 2009-11-09
Posts: 4,010
Website

Re: Post your handy self made command line utilities

jasonwryan wrote:

Play subtitles for a film if they exist

Sorry, I'm a little confused... If a file containing subtitles exists in the same directory as the video and has the same filename (with the exception of the extension) then mpv will automatically use it (and can be toggled with the "v" key).

What feature does your script provide?

Offline

#2754 2016-05-02 14:36:17

Alad
Wiki Admin/IRC Op/TU
From: Bagelstan
Registered: 2014-05-04
Posts: 1,872
Website

Re: Post your handy self made command line utilities

It's common enough that subtitles are named differently, or plain not detected by mpv. Maybe mpv itself should be improved on that regard ...


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby
Honest Alad's Package Emporium—Now with added bugs! (Grand reopening: December 1st 2018)

Offline

#2755 2016-05-03 20:48:15

Earnestly
Member
Registered: 2011-08-18
Posts: 805

Re: Post your handy self made command line utilities

To be fair, mpv should not be responsible for handling subtle differences.  I would require the file name to match exactly as the video file.  Simple.

Offline

#2756 2016-05-04 04:40:14

x33a
Forum Moderator
Registered: 2009-08-15
Posts: 4,565
Website

Re: Post your handy self made command line utilities

Earnestly wrote:

To be fair, mpv should not be responsible for handling subtle differences.  I would require the file name to match exactly as the video file.  Simple.

In my experience mpv and mplayer2 have always worked when the subtitle name matched the video file name. Though I only use srt files, if that makes any difference.

Offline

#2757 2016-05-04 05:33:03

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 26,198
Website

Re: Post your handy self made command line utilities

Yes, the issue it's primarily with subs in a different format (or a non-matching filename).

Now, back to our regular programming...


Arch + dwm   •   Mercurial repos  •   Github

Registered Linux User #482438

Online

#2758 2016-05-07 23:16:54

cryzed
Member
Registered: 2010-05-11
Posts: 12

Re: Post your handy self made command line utilities

I made set-kde-wallpapers to set the KDE desktop wallpaper, screenlocker background and SDDM background separately or all at once from the command-line. Especially setting the SDDM background doesn't work via the KCM currently, so this is a good way around it. The SDDM background is set as suggested by eliasp here.

Use at your own risk, feel free to check out the source code to see what exactly it does and how (it's really short). I use

set-kde-wallpapers PATH

to easily set all three.

Last edited by cryzed (2016-05-07 23:17:37)

Offline

#2759 2016-05-14 10:37:30

karlch
Member
Registered: 2015-06-14
Posts: 104

Re: Post your handy self made command line utilities

Just a really simple and dirty todo list manager inspired by Steve Losh's t

#!/bin/bash

# A very simple todo list manager

# Make the tasks directory
mkdir -p ~/.cache/tasks
taskfile=~/.cache/tasks/tasks

# Check if an argument was given
if [[ $@ ]]; then

    case "$1" in

    # Finish the tasks given in sed format
    f)  sed -i "$2 d" $taskfile
        ;;
    # Sed substitution to edit the task
    s)  sed -i "$2 s/$3/${*:4}/g" $taskfile
        ;;
    # Change the task completely
    c)  sed -i "$2 s/.*/${*:3} ($(date --iso-8601))/g" $taskfile
        ;;
    # Open taskfile in editor
    e)  $EDITOR $taskfile
        ;;
    # Append the task to the task list
    *)  printf "%s (%s)\n" "$*" "$(date --iso-8601)" >> $taskfile
        ;;
    esac

# If there was no argument simply display the tasks with line numbers
else
    cat -n $taskfile
fi

Last edited by karlch (2016-05-14 12:39:16)

Offline

#2760 2016-05-14 11:17:20

Alad
Wiki Admin/IRC Op/TU
From: Bagelstan
Registered: 2014-05-04
Posts: 1,872
Website

Re: Post your handy self made command line utilities

Case statements! Use printf instead of echo. Also, curly braces don't replace quotes;  avoid braces unless they actually add something to your script.

Not sure what you're trying to do with shifting those arguments, but ${@:num} does the same as ${@:num:${#@}}.

Last edited by Alad (2016-05-14 11:18:16)


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby
Honest Alad's Package Emporium—Now with added bugs! (Grand reopening: December 1st 2018)

Offline

#2761 2016-05-14 11:54:54

karlch
Member
Registered: 2015-06-14
Posts: 104

Re: Post your handy self made command line utilities

Thank you Alad for your helpful comments! I have edited the script accordingly.

Out of curiosity, why should I avoid curly braces?

And now with the printf statement I have to quote everything I give as command line argument, otherwise only the first word will be printed. Is there a nice way to avoid this behavior? smile

Offline

#2762 2016-05-14 12:22:34

Alad
Wiki Admin/IRC Op/TU
From: Bagelstan
Registered: 2014-05-04
Posts: 1,872
Website

Re: Post your handy self made command line utilities

Well, unless you're doing parameter substitution, expand arrays, or do ${foo}bar, braces are a no-op. But as long as you quote all the things, it's not a big deal.

Regarding printf, from man bash:

@      Expands  to  the positional parameters, starting from one.  When the expansion occurs within double quotes, each parameter expands to a sepa‐
              rate word.  That is, "$@" is equivalent to "$1" "$2" ...  If the double-quoted expansion occurs within a word, the  expansion  of  the  first
              parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the
              original word.  When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Since you didn't use a formatter, it would be equivalent to:

printf '%s\n' "argument1" "argument2" ...

But there's only one %s, so only one argument is printed. Use $* instead:

printf '%s\n' "$* ..."

Also note: https://github.com/koalaman/shellcheck/wiki/SC2059

Last edited by Alad (2016-05-14 12:23:06)


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby
Honest Alad's Package Emporium—Now with added bugs! (Grand reopening: December 1st 2018)

Offline

#2763 2016-05-14 12:41:53

karlch
Member
Registered: 2015-06-14
Posts: 104

Re: Post your handy self made command line utilities

Thanks again for your help and explanation Alad. Updated the printf statement and it works perfectly now.

The link is great as well, I will definitely use this tool in the future smile

Offline

#2764 2016-05-15 00:04:52

quequotion
Member
From: Oita, Japan
Registered: 2013-07-29
Posts: 657
Website

Re: Post your handy self made command line utilities

Came up with some new ideas for lowest-bid domain management:
/usr/local/sbin/ip-drop

#!/bin/bash

[[ -z "${PROTOCOL}" ]] && PROTOCOL="http://"           # http(s)://, ftp:/, irc:/, etc
[[ -z "${WEBSERVICE}" ]] && WEBSERVICE =""             # :port/path/to/service.ext
[[ -z "${RECIP}" ]] && RECIP="privatekeyholder"        # user who decrypts the email
[[ -z "${SUBJECT}" ]] && SUBJECT="$HOSTNAME woke up!"  # generic "online" message
[[ -z "${EMAILADDR}" ]] && EMAILADDR="user@domain.com" # drop location
[[ -z "${CYCLE}" ]] && CYCLE="86400"                   # 24hrs

PUBLICIP="0.0.0.0"          # In case we aire behind a router, get the internet-facing IP.
                            # Only updates if the address has changed.

while (true) do [[ ! "$(wget -qO- http://ipecho.net/plain)" == "${PUBLICIP}" ]] && \
                   PUBLICIP="$(wget -qO- http://ipecho.net/plain)" && \
                   printf "${PROTOCOL}${PUBLICIP}${WEBSERVICE}" | \
                   gpg --encrypt --recipient "${RECIP}" -o- | \
                   mail -s "${SUBJECT}" "${EMAILADDR}"; \
                   sleep "${CYCLE}"; \
              done

Slight changes to the systemd service:
/etc/systemd/user/ip-drop.service

[Unit]
Description=ip-drop
After=systemd-networkd-wait-online.service
Wants=systemd-networkd-wait-online.service

[Service]
Type=simple
RemainAfterExit=no
ExecStart=/usr/bin/bash "/usr/local/sbin/ip-drop"
StandardOutput=null
StandardError=journal

[Install]
WantedBy=multi-user.target

Note: One could replace "/usr/local/sbin/ip-drop" in ExecStart to make services for other scripts to initiate individual services and ip-drop their url.

As an example, to keep track of an audio broadcast from home:
/usr/local/sbin/queradio

#!/bin/bash

export WEBSERVICE=":8000/queradio.ogg"
export RECIP="zombie"
export SUBJECT="QueRadio"
export EMAILADDR="quequotion@somedomain.com"

ip-drop &

pulsecat | ezstream -c /path/to/queradio.xml

and its systemd service:
/etc/systemd/user/queradio.service

[Unit]
Description=QueRadio
After=icecast.service
Wants=icecast.service

[Service]
Type=simple
RemainAfterExit=no
ExecStart=/usr/bin/bash "/usr/local/sbin/queradio"
StandardOutput=null
StandardError=journal

[Install]
WantedBy=multi-user.target

Last edited by quequotion (2016-06-08 16:02:20)

Offline

#2765 2016-05-15 23:05:01

Saint0fCloud
Member
Registered: 2009-03-31
Posts: 137

Re: Post your handy self made command line utilities

^ Why not just use a dynamic dns service?

Offline

#2766 2016-05-18 13:18:41

quequotion
Member
From: Oita, Japan
Registered: 2013-07-29
Posts: 657
Website

Re: Post your handy self made command line utilities

Saint0fCloud wrote:

^ Why not just use a dynamic dns service?

To avoid having to register anything anywhere and also not spend any money smile

Offline

#2767 2016-05-22 04:20:13

object905
Member
Registered: 2016-04-11
Posts: 11

Re: Post your handy self made command line utilities

This util helps me study english.
Fist shortcut (-Y): notify-send translation of current subtitle string in vlc, second (-G): open google translator.
Use: lvlc [VIDEOFILE] [SRTFILE]

#!/usr/bin/python3
import sys
import socket


if sys.argv[1] == '-G':
    client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    client.connect("/tmp/lvlc_sock")
    msg = '1'.encode('utf-8')
    client.send(msg)
    sys.exit(0)

if sys.argv[1] == '-Y':
    client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    client.connect("/tmp/lvlc_sock")
    msg = '2'.encode('utf-8')
    client.send(msg)
    sys.exit(0)


import os
import subprocess
import pysrt
import telnetlib
import fnmatch
import webbrowser
import urllib.parse
from requests import get
from time import sleep
import logging
import xml.etree.ElementTree


logging.basicConfig(level=logging.INFO)

video_file = os.path.expanduser(sys.argv[1])
if not os.path.isabs(video_file):
    video_file = os.path.abspath(video_file)

sub_file = os.path.expanduser(sys.argv[2])
if not os.path.isabs(sub_file):
    sub_file = os.path.abspath(sub_file)

vlc_rc_host = 'localhost'
vlc_rc_port = 3000
vlc_rc_adr = vlc_rc_host + ':' + str(vlc_rc_port)
vlc = subprocess.Popen(['vlc', '--sub-file', sub_file, '--extraintf', 'rc', '--rc-host', vlc_rc_adr, video_file])

srt = pysrt.open(sub_file)

sleep(3)
telnet = telnetlib.Telnet(vlc_rc_host, vlc_rc_port)
telnet.read_until(b'\r\n')  # greeting message
logging.info('Connected:  {}'.format(vlc_rc_adr))

if os.path.exists("/tmp/lvlc_sock"):
    os.remove("/tmp/lvlc_sock")
server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
server.bind("/tmp/lvlc_sock")


def is_playing():
    telnet.write(b'status\n')
    telnet.read_until(b'\r\n');telnet.read_until(b'\r\n')
    stat = telnet.read_until(b'\r\n').decode('utf-8')
    if 'playing' in stat:
        return True
    else:
        return False


def get_time():
    telnet.write(b'get_time\n')
    buf = telnet.read_until(b'\r\n').decode('utf-8')
    time_sec = int(''.join(fnmatch.filter(buf, '[0-9]')))
    logging.info('get_time: {}'.format(time_sec))
    return time_sec


def make_time_tuple(time_seconds, milli_sec=0):
    hours = time_seconds // 3600
    minutes = (time_seconds - hours * 3600) // 60
    seconds = time_seconds - ((hours * 3600) + (minutes * 60))
    return hours, minutes, seconds, milli_sec


def open_google(text_for_translation):
    data = urllib.parse.urlencode({'t': text_for_translation}).replace('t=', '')
    url = 'https://translate.google.ru/?hl=en&tab=TT#en/ru/' + data
    webbrowser.open(url)


def yandex_translate(text_for_translation):
    par = {'key': HERE: https://tech.yandex.ru/translate/', 'lang': 'ru',
           'text': text_for_translation}
    resp = get('https://translate.yandex.net/api/v1.5/tr.json/translate?', params=par)
    trans_text = eval(resp.text)['text'][0]
    subprocess.Popen(['notify-send', ' ', trans_text])


while True:
    what_do = server.recv(8).decode('utf-8')
    print(what_do)

    current_time = get_time()
    timestamp = make_time_tuple(current_time)

    try:
        text = srt.at(timestamp)[0].text
        logging.info(text)
    except IndexError:
        text = False

    if text and is_playing():
        telnet.write(b'pause\n')

    if text:
        try:
            text = ''.join(xml.etree.ElementTree.fromstring(text).itertext())  # remove html tags
        except Exception:
            pass

        text = text.replace('\n', ' ')

        if what_do == '1':
            open_google(text)
        else:
            yandex_translate(text)

Last edited by object905 (2016-06-01 13:34:30)

Offline

#2768 2016-05-29 16:45:15

Chazza
Wiki Maintainer
From: United Kingdom
Registered: 2013-06-02
Posts: 506

Re: Post your handy self made command line utilities

This is an applications menu generator for some window managers. It's like archlinux-xdg-menu except for the fact that it has icon support (which archlinux-xdg-menu doesn't seem to have), and it also has some other features like command line options for excluding entries and categories and support for custom categories like Chromium Apps. It's written in C++ (as I'm a C++ novice and wanted to get some practice) so apologies if this is meant to be for scripting languages only.

https://github.com/charlesbos/mwmmenu

Edit: archlinux-xdg-menu does have icon support for some window managers but icon support for others (like FVWM) appears to have been left out (to the best of my knowledge).

Last edited by Chazza (2016-05-29 18:26:47)

Offline

#2769 2016-05-29 17:40:58

parchd
Member
Registered: 2014-03-08
Posts: 421

Re: Post your handy self made command line utilities

Chazza wrote:

This is an applications menu generator for some window managers. It's like archlinux-xdg-menu except for the fact that it has icon support (which archlinux-xdg-menu doesn't seem to have), and it also has some other features like command line options for excluding entries and categories and support for custom categories like Chromium Apps. It's written in C++ (as I'm a C++ novice and wanted to get some practice) so apologies if this is meant to be for scripting languages only.

https://github.com/charlesbos/mwmmenu

What window manager do you use? I'm sure that archlinux-xdg-menu supports icons for openbox (much to my personal distaste, at least with the theme I use).

Offline

#2770 2016-05-29 18:07:24

Chazza
Wiki Maintainer
From: United Kingdom
Registered: 2013-06-02
Posts: 506

Re: Post your handy self made command line utilities

Ah so it does. But I use FVWM and archlinux-xdg-menu doesn't support icons for that. I'll amend my post.  My utility can toggle icons on and off (for the window managers that support it).

Last edited by Chazza (2016-05-29 18:08:19)

Offline

#2771 2016-05-29 19:18:34

moetunes
Member
From: A comfortable couch
Registered: 2010-10-09
Posts: 1,030

Re: Post your handy self made command line utilities

Chazza wrote:

This is an applications menu generator for some window managers. It's like archlinux-xdg-menu except for the fact that it has icon support (which archlinux-xdg-menu doesn't seem to have), and it also has some other features like command line options for excluding entries and categories and support for custom categories like Chromium Apps. It's written in C++ (as I'm a C++ novice and wanted to get some practice) so apologies if this is meant to be for scripting languages only.

https://github.com/charlesbos/mwmmenu

I don't think multi filed C++ programs fall into the category of "handy self made command line utilities"...
Maybe community contributions would be more appropriate.


You're just jealous because the voices only talk to me.

Offline

#2772 2016-06-04 21:16:34

dimich
Member
From: Kharkiv, Ukraine
Registered: 2009-11-03
Posts: 50

Re: Post your handy self made command line utilities

Hi

I've written following script to monitor internet connection state:

#!/bin/bash

########## Options #########
# IP2CHECK and INTERVAL variables must be defined there
source /etc/inetmon.conf

########## Stuff ###########
QUIT=0
trap "QUIT=1" SIGINT SIGTERM

# Assume connection is on by default
OLD_STATE=0
PERIOD=${INTERVAL}

notify()
{
    logger "$1"

    for i in /tmp/.X11-unix/X*; do
        DISPLAY=":${i: -1}" notify-send "$1"
    done
}

########## Main loop ########
while true; do
    ping -4 -W 1 -c 3 ${IP2CHECK} > /dev/null 2>&1
    NEW_STATE=$?

    if [ "${QUIT}" -ne 0 ]; then break; fi

    if [ ${OLD_STATE} -lt ${NEW_STATE} ]; then
        # Connection is down
        notify "Connection is down"
        PERIOD=0
    elif [ ${OLD_STATE} -gt ${NEW_STATE} ]; then
        # Connection is up
        notify "Connection is up"
        PERIOD=${INTERVAL}
    fi
    OLD_STATE=${NEW_STATE}

    if [ ${PERIOD} -ne 0 ]; then sleep ${PERIOD}; fi
    if [ "${QUIT}" -ne 0 ]; then break; fi
done

echo "Terminated"

Examplary /etc/inetmon.conf:

IP2CHECK=8.8.8.8
INTERVAL=10

Systemd unit for startup:

[Unit]
Description=Displays internet connection on/off notifications
After=network.target

[Service]
ExecStart=/path/to/script

[Install]
WantedBy=multi-user.target

Maybe someday i'll improve it and make AUR package.

Last edited by dimich (2016-06-04 21:17:31)

Offline

#2773 2016-06-05 04:03:50

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

Re: Post your handy self made command line utilities

this is small script to open bookmarks/history with dmenu, works with any browser. boomarks & history file should be plain text or html, script will find url from it.
this script is not entirely mine, part of it is from "boosta-view" on github, w3m specific version usin rofi is here, along with dmenu based duckduckgo search script.

#!/bin/bash

 grep -o 'http[^"]*' "<bookmarks-file>" > /tmp/bookmarks
 grep -o 'http[^"]*' "<history-file>" >> /tmp/bookmarks


 LAUNCHER='dmenu -p Bookmarks:'
 BROWSER='<your-browser>'
 BOOKMARKS="/tmp/bookmarks"

 url=`cat $BOOKMARKS | $LAUNCHER | awk -F '|' '{printf("%s ", $NF)}' | tr -d '\r\n'`

 if [ ${#url} -gt 0 ]
 then
 $BROWSER $url
 fi

Arch is home!
i3 rofi w3m vimb ranger vim mutt lizzy pass

Offline

#2774 2016-06-07 13:03:18

easysid
Member
From: India
Registered: 2013-01-01
Posts: 256

Re: Post your handy self made command line utilities

A script to tag and fetch windows in bspwm. It stores a window id with the mark/tag and uses it later to pull the tagged window to the current desktop. Not sure if using a file is the best way to achieve this, but this info has to be stored somewhere.

#!/bin/bash
# tagfetch.sh
# script to tag and fetch windows in bspwm

[[ $# -ne 2 ]] && exit 101
# create a directory for storing id info
tagdir="/tmp/tagdir"
[[ -d $tagdir ]] || mkdir "$tagdir"
# use 1 file per tag
tagfile="$tagdir/$2"
case $1 in
    tag)
        echo -n $(bspc query -N -n) > "$tagfile"
        ;;
    fetch)
        [[ -f $tagfile ]] && bspc node $(< $tagfile) -d $(bspc query -D -d)
        ;;
esac

bind it to sxhkd to mark, and fetch windows

# tag
super + ctrl + {1-9}
    tagfetch.sh tag {1-9}
#fetch
super + shift + {1-9}
    tagfetch.sh fetch {1-9}

Offline

#2775 2016-06-08 04:50:55

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

Re: Post your handy self made command line utilities

I don't use bspwm so I am not sure, but probably you can use "rofi", to get open windows.


Arch is home!
i3 rofi w3m vimb ranger vim mutt lizzy pass

Offline

Board footer

Powered by FluxBB