You are not logged in.

#3201 2018-10-03 13:58:49

eschwartz
Trusted User/Bug Wrangler
Registered: 2014-08-08
Posts: 2,556

Re: Post your handy self made command line utilities

Trilby wrote:

Eschwartz, to be fair, they didn't sed pacman.conf themselves.  They read pacman.conf line by line in a clumsy and pointless loop and sed''ed part of each line for no reason only to check whether it matched 'IgnorePkg' and then only to oddly and conditionally append a space then a value to a simple variable when an array would be much easier needing no conditional or spaces.

And this is you being "fair"... tongue

Honest, yes, I will grant you that. But generally the phrase "to be fair" is used by people extending mercy, not additional objections. big_smile

If pacman-conf were not an option, that entire loop could just be:

IGNORE=$(sed -n 's/^IgnorePkg[^=]*=//p' /etc/pacman.conf)
# or better as an array
IGNORE=($(sed -n 's/^IgnorePkg[^=]*=//p' /etc/pacman.conf))

If it comes to that, matching on 'IgnorePkg222 = nope' and finding that the "nope" package should be ignored, is rather erroneous...

Don't match:

^IgnorePkg[^=]*=

Do match:

^IgnorePkg[[:space:]]*=

Managing AUR repos The Right Way -- aurpublish (now a standalone tool)

Offline

#3202 2018-10-03 14:01:01

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

Re: Post your handy self made command line utilities

Good revision to my sed command.  To be fair, I'm an idiot. tongue


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

Offline

#3203 2018-10-03 15:31:43

Crouze
Member
Registered: 2017-10-04
Posts: 12

Re: Post your handy self made command line utilities

And to be fair, learned something new again today. Of course there was an easier way wink

Offline

#3204 2018-10-05 08:47:36

kokoko3k
Member
Registered: 2008-11-14
Posts: 1,762

Re: Post your handy self made command line utilities

I've found this nice site that is missing an rss but gives you updates about new free games, so i wrote a little script that checks it and send me a notification when there is a new free game; didn't tested it deeply... yet!
It uses the handy "sendemail" tool from aur.

#!/bin/bash
wdir=/koko/scripts/gamecheck
f1="$wdir/1.txt"
f2="$wdir/2.txt"
mkdir "$wdir" &>/dev/null
interval=7200 #secs

function notify() {
	 /usr/bin/sendEmail \
		-f source_email@gmail.com \
		-t dest_email@gmail.com \
		-s smtp.gmail.com:25 \
		-xu gmail_username \
		-xp gmail_password \
		-u "GameCheck" \
		-m "New updates on: https://givemekey.com/?s=" 
}

function check_out() {
	curl "https://givemekey.com/?s=" |\
		tr "<" "\n"|\
		grep free |\
		grep "title\=" |\
		cut -d \" -f 2
}

check_out > "$f1"

while true ; do
	sleep $interval
	check_out > "$f2"
	if [ $(<"$f1") != $(<"$f2") ] ; then
		notify "$f2"
	fi
	cp "$f2" "$f1"
done

...and a systemd service as well

[Unit]
Description=Check for free games

[Service]
Type=simple
ExecStart=/home/koko/scripts/gamecheck.sh

[Install]
WantedBy=default.target

Last edited by kokoko3k (2018-10-05 08:55:15)

Offline

#3205 2018-10-24 13:28:47

kokoko3k
Member
Registered: 2008-11-14
Posts: 1,762

Re: Post your handy self made command line utilities

This one will set the same "custom" refresh and resolution for all of the connected monitors.
I use it as a convenient way to play games with lower refresh rates when my GPU can't handle more.

#!/bin/bash

if [ ! $# = 2 ] ; then
	echo Example $(basename $0) 1280x1024 75
	exit
fi

w=$(cut -d "x" -f 1 <<< "$1")
h=$(cut -d "x" -f 2 <<< "$1")
hz=$2

#Genera la modeline
	GTF_OUT=$(gtf $w $h $hz|grep Modeline)
	MODE_NAME=koko_"$w"x"$h"_"$hz"
	TIMINGS=$(grep Modeline <<< $GTF_OUT |cut -d \" -f 3)
	MODELINE="$MODE_NAME $TIMINGS"

#aggiungo al pool:
	xrandr --newmode $MODELINE
	
#Aggiunge e setta il modo custom a tutti i monitor
	MONITORS=$(xrandr|grep " conne"|cut -d " " -f 1|tr \\n " ") 

	for MONITOR in $MONITORS ; do
		xrandr --addmode $MONITOR $MODE_NAME
		xrandr --output $MONITOR --mode $MODE_NAME
	done

	echo "Press ENTER in 10 seconds to keep settings"
	read -n 1 -t 10
	if [ ! $? == 0 ]; then
		#Cleanup:
		for MONITOR in $MONITORS ; do
			xrandr --output $MONITOR --preferred
			xrandr --delmode $MONITOR $MODE_NAME
			xrandr --rmmode $MODE_NAME
		done
	fi

EDIT:
removed 2 useless echo, before someone pointed it out; ready for the next tongue

Last edited by kokoko3k (2018-10-24 13:33:43)

Offline

#3206 2018-10-24 13:59:36

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

Re: Post your handy self made command line utilities

You seem to do a lot of munging of variables only to undo it later.  For example, you have a subshell and pipeline to extract the width an height from $1, but then later you use "$w"x"$h" to put them back together.  You only need the individual width and height values once, so just extract them there, and use shell builtins to do it, e.g.:

timings=$(gtf ${1%x*} ${1#*x} $2 | awk '/Modeline/ { print $3; }')

Also note, the use of awk instead of grep and cut.
I can't test it, but the following should do the same thing as your script:

#!/bin/sh

if [ ! $# = 2 ] ; then
	echo Example $(basename $0) 1280x1024 75
	exit
fi

modename="koko_$1_$2"

xrandr --newmode $modename "$(gtf ${1%x*} ${1#*x} $2 |  awk '/Modeline/ { $1=""; $2=""; print; }')"

monitors=$(xrandr | awk '/ connected/ { print $1; }')

for monitor in $monitors; do
	xrandr --addmode $monitor $modename
	xrandr --output $monitor --mode $modename
done

read -p "Press ENTER in 10 seconds to keep settings" -n 1 -t 10 && exit

for monitor in $monitors; do
	xrandr --output $monitor --preferred
	xrandr --delmode $monitor $modename
done
xrandr --rmmode $modename

One thing that stands out is that almost all of the output of gtf is completely ignored - only the timing value is extracted and passed to xrandr's --newmode.  Is this really how that should work? (edit: ah, I misunerstood your cut pipeline, I've modified my version to get the equivalent output from gtf.)

Last edited by Trilby (2018-10-24 14:05:48)


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

Offline

#3207 2018-10-24 14:19:26

kokoko3k
Member
Registered: 2008-11-14
Posts: 1,762

Re: Post your handy self made command line utilities

Trilby wrote:

You seem to do a lot of munging of variables only to undo it later.

D'oh, you're right ^_^

Also note, the use of awk instead of grep and cut.

Unfortunately i'm not really familiar with it; i've to sort it out.

...apart from that, i prefer to use more and descriptive variables so that i'll not spend too much time next time to understand what i wrote.

Offline

#3208 2018-10-24 14:39:22

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

Re: Post your handy self made command line utilities

You can still name variables and be more verbose than my examples without needing to use subshells with long pipelines:

...

width=${1%x*}
height=${1#*x}

timings=$(gtf $width $height ...)

My personal style is to never create a variable for something that will only be used once, unless the calculation of the value is pretty complex so that splitting off the calculation (and assignment) to a new line makes it easier to read.  In this case "${1%x*}" is quite short, and never reused, so I'd personally not use a variable for it - but that's a stylistic choice.


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

Offline

#3209 2018-11-13 12:25:00

sjmulder
Member
Registered: 2018-11-13
Posts: 11

Re: Post your handy self made command line utilities

Man I just love writing little programs. Here's a few that may be useful:

json-yaml

Converts JSON to YAML for easy reading (or further processing):

$ curl -s http://api.icndb.com/jokes/random | ./json-yaml
type: success
value:
  id: 415
  joke: When Chuck Norris wants an egg, he cracks open a chicken.
  categories: []
nostt

A command line NOS Teletekst reader (a Dutch teletext system, like BBC's Ceefax).

within

My favourite one. Run a command in other directories:

$ within code/* - git status
code/json-yaml: nothing to commit, working tree clean
code/nostt: nothing to commit, working tree clean
code/within: nothing to commit, working tree clean
code/dated: nothing to commit, working tree clean
dated

Adds a timestamp to every line:

$ tail -f test.txt | dated
11/07/18 21:28:31 Hello
11/07/18 21:28:40 World!
$ tail -f test.txt | dated -f "[%H:%M] "
[21:32] Hello
[21:33] World!

Of course there are AUR packages for all of them big_smile

Offline

#3210 2018-11-25 21:33:33

brett
Member
Registered: 2018-04-21
Posts: 4

Re: Post your handy self made command line utilities

I like to have these functions loaded at login (i have them in my .aliases file) to have them at the ready:

This one helps me quickly fire up a new database to quickly start a new project

function mkdb() {
echo
if [ 2 -gt  $# ] ;then 
      echo "mkdb - invalid parameters"
      echo "** usage: mkdb database_name [user_name] password"
      echo "** if user_name is not specified database_name will be used also for user_name"
else
	db_name=$1

	if [ $# -gt 2 ]
	then
		user_name=$2
		pass=$3
	else
		user_name=$1
		pass=$2
	fi

	echo
	echo "Creating database '$db_name' and user '$user_name' and granting access to database to the new user."
	
	mysql -u root  --execute="CREATE USER IF NOT EXISTS '$user_name'@'localhost' IDENTIFIED BY '$pass';GRANT USAGE ON *.* TO '$user_name'@'localhost' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;CREATE DATABASE IF NOT EXISTS $db_name;GRANT ALL PRIVILEGES ON $db_name.* TO '$user_name'@'localhost';"
fi
echo 
}

This one I use to swap hosts lists based on my needs: when developing I like to have all my project domains pointing to 127.0.0.1, and when I deploy i like to see them live. This makes the deploy easier, no need to search and replace for 'localhost' in the project files (or db dump).

#rotate hosts files
function chost {
  set -e # stop running if we encounter an error
  if [[ ! -f  /etc/hostssecondary ]]; then
      sudo \touch /etc/hostssecondary
  fi  
  echo
  echo --------------------------------------------
  sudo \mv -f /etc/hosts /etc/hoststempname
  sudo \mv -f /etc/hostssecondary /etc/hosts
  sudo \mv -f /etc/hoststempname /etc/hostssecondary
  set +e
  cat /etc/hosts
  echo
  echo --------------------------------------------
  echo
}

Offline

#3211 2018-11-25 21:48:11

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

Re: Post your handy self made command line utilities

You could just set pass to the last argument, user to the first argument, then really simplify that conditional to a single line:

[ $# -gt 2 ] && user_name=$2

If you are using BASH getting the last argument is just array manipulation, but from the single [ I'd gather you may not be using (exclusively) BASH, so you can use a for loop:

db_name= $1
user_name=$1
[ $# -gt 2 ] && user_name=$2
for arg; do :; done
pass=$arg

Last edited by Trilby (2018-11-25 22:40:08)


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

Offline

#3212 2018-11-25 21:59:01

brett
Member
Registered: 2018-04-21
Posts: 4

Re: Post your handy self made command line utilities

great tips, thanks

for the first one, i'd normally add the optional parameter at the end, but in this case I rather wanted to have the natural flow of thought on usage, even if it meant I'd have to do a bit of code acrobatics for this end.

Offline

#3213 2018-12-03 10:22:11

Stencon281
Member
Registered: 2016-09-21
Posts: 40

Re: Post your handy self made command line utilities

I use emacs with transparency enabled and this script helps me follow tutorials / documentation more easily.

Seems a little esoteric, but it's really nice being able to switch focus to your webbrowser without losing site of your text editor and switch tabs, play/pause a video, go to a url, etc...

I have it bound to Hyper-w, pressing it once will switch focus to firefox, pressing it consecutively is the same as alt-tab selecting firefox.

#!/bin/bash

focus="$(xdotool getwindowfocus)"

# if firefox exists in the current desktop
firefox="$(xdotool search --desktop "$(xdotool get_desktop)" --name "Firefox")"

# if firefox is running
firefoxExists="$(wmctrl -l | grep Firefox)"

if [[ -z $firefoxExists ]];then
  # firefox isn't running, launch it
  firefox &
  wmctrl -a "Firefox"
  wmctrl -r "Firefox" -N "$BROWSER"
  
  # delay to account for button debounce
  
  sleep .5

elif [[ $firefox ]];then
  
  # firefox is running and exists in the current desktop
  
  visible="$(xdotool search --desktop "$(xdotool get_desktop)" --onlyvisible --name "Firefox")"
  exists="$(xdotool search --desktop "$(xdotool get_desktop)" --name "Firefox")"

  if (($firefox != $focus)); then
    
    # firefox isn't focused (or it could be minimized), raise it without
    # bringing it to the front of the window stack
    
    wmctrl -r "Firefox" -b add,below

  elif (($firefox == $focus)); then
    
    # firefox is focused, make it the top most window
    
    wmctrl -r "Firefox" -b remove,below
    xdotool search --desktop "$(xdotool get_desktop)" --name "Firefox" windowraise
  fi
  
  # select window with the name "Firefox"
  
  wmctrl -a "Firefox"
fi

# wmctrl -r "Firefox" -N $BROWSER

Offline

#3214 2018-12-03 15:02:00

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

Re: Post your handy self made command line utilities

Just install a tiling window manager tongue


Arch + dwm   •   Mercurial repos  •   Github

Registered Linux User #482438

Offline

#3215 2018-12-03 15:09:46

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

Re: Post your handy self made command line utilities

emacs is a tiling window manager among many other things, isn't it?

Install a good tiling window manager (and a text edtior while you're at it! tongue )

Last edited by Trilby (2018-12-03 15:10:11)


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

Offline

#3216 2018-12-04 08:24:47

Stencon281
Member
Registered: 2016-09-21
Posts: 40

Re: Post your handy self made command line utilities

jasonwryan wrote:

Just install a tiling window manager tongue

i just use xfwm since i prefer my windows full screened, seeing spaces between windows distracts me.

Trilby wrote:

emacs is a tiling window manager among many other things, isn't it?

Install a good tiling window manager (and a text edtior while you're at it! tongue )

the defaults for all text editors are bad, i use my own superior version of emacs, which is more of a work of art (as intended) than it is some finely tuned work tool with the specifications of its original maker

all in all my script could use a little work now that i'm looking closely at it... hrmmmm..... also using terminal text editors feels so clunky after i've experienced the full power of the gui!

Offline

#3217 2018-12-04 15:57:19

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

Re: Post your handy self made command line utilities

Stencon281 wrote:

i just use xfwm since i prefer my windows full screened, seeing spaces between windows distracts me.

In compiz, you can use the "Place" and "Window Rules" plugins to mandate certain programs to open on specific viewports and always be fullscreen. It also has a handy drop-zone tiling plugin, and you can see through windows using the "Opacity, Brightness, and Saturation" plugin. In addition, all desktop and window management can be mouse-operated smile *never used emacs in my life*

more of a work of art (as intended) than it is some finely tuned work tool

For the artist who makes or modifies his own tools, is there a difference?

Last edited by quequotion (2018-12-04 15:58:29)

Offline

#3218 2018-12-04 20:49:55

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

Re: Post your handy self made command line utilities

This is a script that i wrote for maintaining my gentoo boxes at home.nothing fancy, just makes everything a bit faster.

#!/bin/bash

# each item you want to prompt about in order
order=(eix revdep world depclean update ecleanpkg ecleandist news)

# prompt string hash for each item
declare -A prompts=(
	[eix]="Sync custom package repository and the Gentoo ebuild repository using eix"
	[revdep]="Check for and rebuild missing libraries (not normally needed)"
	[world]="Update world"
	[depclean]="Remove packages no longer needed"
	[update]="Manage configuration changes after an emerge completes"
	[ecleanpkg]="Cleaning packages"
	[ecleandist]="Clean the source files directory by passing the distfiles argument"
    [news]="Read news."
)

# the command for each item
eix=(eix-sync)
revdep=(revdep-rebuild -i -- -av)
world=(emerge -avuND @world)
depclean=(emerge -avc)
update=(etc-update)
ecleanpkg=(eclean-pkg)
ecleandist=(eclean-dist)
news=(eselect news read)

for item in "${order[@]}" ; do
	prompt="${prompts[$item]}"

	# don't try this at home
	eval "command=(\"\${$item[@]}\")"

	while read -n 1 -r -p "$prompt: (Y/n): " ; do
		case "$REPLY" in
			# permit the user to hit enter to get the default behavior
			[Yy]|'')
				# commands are always run with sudo
				sudo "${command[@]}"
				break
			;;
			[Nn])
				echo
				break
			;;
			*)
				printf '\nUnrecognized response "%s". please use Y or N\n' "$REPLY"
			;;
		esac
	done
done
 

Offline

#3219 2018-12-09 15:34:44

ugjka
Member
From: Latvia
Registered: 2014-04-01
Posts: 1,169

Re: Post your handy self made command line utilities

Getting root ssh on my LTE modem/router https://github.com/ugjka/B593s-22_SSH


Github | Soundcloud

"Once you hit 10 nested VMs you're basically brad pitt with women who matter" ~ echoline

Offline

#3220 2018-12-10 18:17:13

ackt1c
Member
From: Visalia, California
Registered: 2012-10-10
Posts: 231

Re: Post your handy self made command line utilities

I wanted a calendar in dwm and found the 'cal' command. so..

#!/bin/bash
#urxvt -g 20x8+1280 -e calendar
cal;
sleep 7;
exit;

using urxvt's geometry (first commented command) i can make it just small enough and put it next to the systray, edited config.h for ClkStatusText and now i have a calendar (i also bound it to meta+c)

Offline

#3221 2018-12-10 21:20:29

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

Re: Post your handy self made command line utilities

Note that there is no need for those semicolons.  Nor is there a need for an exit command at the end of a script.  And with those two points there becomes no need for the script.  Just bind the command you want:

urxvt -g 20x8+1280 -e sh -c "cal && sleep 7"

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

Offline

Board footer

Powered by FluxBB