You are not logged in.

#3176 2018-04-12 23:15:23

Awebb
Member
Registered: 2010-05-06
Posts: 5,037

Re: Post your handy self made command line utilities

I'm not checking for "anything in stdout", I'm checking for a boolean. If "git pull" succeeds it returns true, if not it returns false. That's what the whole [[ $(git pull) ]] was about. The other function uses cower to check, whether the update is required. The pull command is not being called, unless the repo isn't there yet or the updater calls it, because cower said so. But yeah, I guess I could rewrite the thing with what you told me and ditch cower to check for updates.

Offline

#3177 2018-04-12 23:30:32

Eschwartz
Trusted User/Bug Wrangler
Registered: 2014-08-08
Posts: 1,846

Re: Post your handy self made command line utilities

Eschwartz wrote:

Currently you're checking that by seeing whether anything is emitted to stdout. -_-

It is most certainly not a boolean in any way. That is command substitution: http://wiki.bash-hackers.org/syntax/expansion/cmdsubst

As an additional degree of "what?????", the test construct [[ ... ]] does not care which type of boolean you substitute (even when you're actually substituting the text "Updating bed4637..a852ab1" or possibly the text "Already up to date."), because it defaults to the test -n operator:

man test wrote:

       -n STRING
              the length of STRING is nonzero

Both boolean 0 and boolean 1 have a nonzero length...

...

I assumed if you're looking at stdout instead of `if ! cmd`, then you care about that specifically; which, however, only happens when you get network fetch errors. Apparently I'm totally wrong. hmm

Last edited by Eschwartz (2018-04-12 23:40:05)

Offline

#3178 2018-04-13 08:22:06

Awebb
Member
Registered: 2010-05-06
Posts: 5,037

Re: Post your handy self made command line utilities

Eschwartz wrote:

Apparently I'm totally wrong. :/

What I wanted to do and what I did seem to be two different things. I didn't know it defaults to -n. I tried the if statement with and without the test brackets and you are totally right!

About the git commands, to clarify what I wanted to do with pull and a test:

A 'git pull || echo "ERROR"' in a folder with a proper .git does not create an error if either the repo was up-to-date or if something was pulled. In a folder without a .git subfolder and anywhere git pull fails, it'll look like this:

$ git pull || echo "ERROR"
fatal: not a git repository (or any of the parent directories): .git
ERROR

Offline

#3179 2018-04-22 15:52:12

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

Re: Post your handy self made command line utilities

Threw this together to make a series of demos for Pantheon 3D.

I know the way I'm getting the desktop size isn't optimal; suggestions welcome!

#!/bin/bash
##############################################################################
# This script starts a desktop recording with a desktop notificaiton caption.
#
# Caption options:
# $0                     "Desktop, recording..."
# $0 title               "Title, recording..."
# $0 title summary       "Title, explanation"
# $0 title summary body  "Title, explanation, detail"
#
# Specify FPS=number for your desired framerate (defaults to 30fps)
# Specify SIZE=LENGTHxWIDTH for your desktop size (defaults to get size from xrandr)
# Specify DELAY=seconds for your desired delay (defaults to 10s)
############################################################################## SETUP
[[ ! -d ~/Videos/Desktop/ ]] && mkdir -p ~/Videos/Desktop/ &

[[ -z ${FPS} ]] && FPS="30"
[[ -z ${SIZE} ]] && SIZE="$(xrandr | grep current | sed 's|.*current\ ||g;s|,.*||g;s|\ ||g')"
[[ -z ${DELAY} ]] && DELAY="10"
[[ -z ${DESKRECOPTS} ]] && DESKRECOPTS="-f x11grab -s ${SIZE} -r ${FPS} -i :0.0"
############################################################################## LOGIC
if [ -z "${1}" ]; then
  TITLE="Desktop"
  SUMMARY="recording..."
else
  TITLE="${1}"
  if [ -z "${2}" ]; then
    SUMMARY="recording..."
  else
    SUMMARY="${2}"
    if [ -z "${3}" ]; then
      BODY=""
    else
      BODY="${3}"
    fi
  fi
fi
############################################################################## EXECUTION
sleep "${DELAY}" && notify-send -t 1500 -a "${TITLE}" "${SUMMARY}" "${BODY}" && exec ffmpeg $DESKRECOPTS ~/Videos/Desktop/"$(date +%F-%T)"-"${*}".mp4

Depends on libnotify for sending notifications, xrandr to get desktop size, and ffmpeg for recording.
Lately I've been using Dunst for displaying notifications.

Last edited by quequotion (2018-04-29 08:16:26)

Offline

#3180 2018-04-25 19:12:38

scar
Member
From: Hungary
Registered: 2009-10-01
Posts: 428

Re: Post your handy self made command line utilities

Well, a week ago or so I installed the google earth view extension for my chromium browser.
It is a funny little thing, which, at the opening of a new tab, puts a full-browser-size image in that tab, from google earth. The images are really nice.
Downloading that image and setting it as a background, is also nice, so this is what I did (and I kick it at every session launch, so I have a nice rotation of the backgrounds.)
As you'll see, I use xfce, but substitute it with your command for setting a backdrop. Here's the script:

# COPYRIGHT AND LEGAL STUFF ABOUT OF THE IMAGE CONTENT: 
#
# Google ©2018 Cnes/Spot Image, DigitalGlobe

#earthviewbackdrop.sh
#!/bin/bash

while [ ! -f $j.jpg ]
do

    j=$(((RANDOM%1198+1101)))
   wget https://earthview.withgoogle.com/download/$j.jpg

done

   mv $j.jpg /home/YOURHOMEHERE/Pictures/background.jpg
   xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image --set /home/YOURHOMEHERE/Pictures/background.jpg

#END

“The future has already arrived. It's just not evenly distributed yet.”
― William Gibson

Offline

#3181 2018-05-08 01:17:30

anselm
Member
Registered: 2016-05-11
Posts: 113

Re: Post your handy self made command line utilities

Sometimes hard to find files on the hard drive, because I don't remember where I saved. Sometimes I remember some part of the name, or I simply want to look for any extension. This is why I wrote Ruby script "find_and_link <search_in> <link_into> <pattern>". Its mere purpose is: traverse the directory tree recursively starting from the directory "search_in", finding all files which names are matching to the given "pattern", and then makes a softlink for them in the directorty <link_into>. Sometimes files can have same name, in this case the script apply numeric prefixes for the softlink filenames in the "link_into" dir, like 0001, and so on.

#!/usr/bin/ruby
require 'find'
require 'shellwords'
require "time"


search_in=ARGV[0]
link_into=ARGV[1].chomp("/")
pattern=ARGV[2]
regex=Regexp.new(pattern,"i")
puts regex.inspect

n=0
Find.find(search_in) do |path|
  #puts path if n % 100 ==0
  n+=1
  if FileTest.directory?(path)
    if File.basename(path)[0] == '.'
      Find.prune       # Don't look any further into this directory.
    else
      next
    end
  else
    STDOUT.puts path
    STDERR.puts path
    next
  
    if File.basename(path) =~ regex  then
      puts path 
      
      if true then
        begin
			if true then
				puts "-"*70
				puts path
				puts "-"*70
				link_to="#{link_into}/#{File.basename(path)}"
				prefix=""
				index=0
				while File.exist?(link_to) 
				   prefix="#{"%03d" % index}_"
				   index+=1
				   link_to="#{link_into}/#{prefix}#{File.basename(path)}"
				   
				end
				%x{ln -s "#{path}" "#{link_into}/#{prefix}#{File.basename(path)}" }
			end
		rescue => e
		  puts e
		  puts e.backtrace.inspect
		  
		end
      end
    end
  end
end

Script contains two seemingly illogic statement "if true then" because earlier I used it to find mp3 files which duration is greater than a given value, but later I removed that code sections. Pattern isn't bash glob pattern, but Ruby compatible regex, for examle finding mp3 files, regex should be "\.mp3$"

Offline

#3182 2018-05-08 02:10:10

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

Re: Post your handy self made command line utilities

Ah ... anselm, read `man find`

find $search_in -name $pattern -exec ln -s -t $link_into '{}' \+

Or, depending on your needs for the pattern

find $search_in -regex $pattern -exec ln -s -t $link_into '{}' \+

Plus you then have access to all the other `find` conditional tests for file size (proxy for mp3 duration) or age etc.

Last edited by Trilby (2018-05-08 02:14:33)


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

Offline

#3183 2018-05-08 03:19:47

anselm
Member
Registered: 2016-05-11
Posts: 113

Re: Post your handy self made command line utilities

Yes, much shorter, but this doesn't apply prefixes for the case of filename collisions, so that hits will be missing from the dir of the softlinks.

Last edited by anselm (2018-05-08 03:21:54)

Offline

#3184 2018-05-08 10:19:03

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

Re: Post your handy self made command line utilities

Then add that as needed:

find $search_in -regex $pattern -exec ln --backup=numbered -s -t $link_into '{}' \+

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

Offline

#3185 2018-05-17 08:22:22

xvzf
Member
Registered: 2014-05-18
Posts: 86

Re: Post your handy self made command line utilities

This is what I am using for backups with ZFS since a 3/4 year!
https://github.com/xvzf/dataleech

It is now also in the AUR!

Offline

#3186 2018-05-18 17:59:30

mankand007
Member
From: Chennai, India
Registered: 2012-02-26
Posts: 43
Website

Re: Post your handy self made command line utilities

Here's a quick script I made to display the time since last pacman system update in conky. Hope somebody finds this useful.

#!/bin/sh
i=$(($(date +%s) - $(date -r /var/log/pacman.log +%s)))
((days=i/86400, i-=days*86400, hrs=i/3600, i-=hrs*3600, min=i/60, i-=min*60, sec=i))
printf "%dd %02dh %02dm %02ds" $days $hrs $min $sec

Custom built Openbox Arch linux 64

blog:
http://manikandan.means.it

Offline

#3187 2018-05-21 14:24:31

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 15,687

Re: Post your handy self made command line utilities

I was bored, on a plane, and decided to pass some time to learn about Bash arrays.  This program generates a simple maze when run.
Any comments on how to improve?  Bash is not my forte.

#! /bin/env bash

deltaX=(-1  0 1 0 )
deltaY=( 0 -1 0 1 )

push() {
    # Remember the current location.
    xStack+=($xLoc)
    yStack+=($yLoc)
}

pop(){
    # Get the last location we saved anf make it the current location
    xLoc=${xStack["${#xStack[@]}-1"]}
    yLoc=${yStack["${#yStack[@]}-1"]}
    unset 'xStack[${#xStack[@]}-1]'
    unset 'yStack[${#yStack[@]}-1]'
}

makeHole() {
    #Turn a wall into a path at out current location
    theMap[yLoc*width+xLoc]=' '
}

getDirs(){
    # Find out how many directions we can go from here without creating loops.
    dirs=()
    for ((i=0; i<4 ; i++)); do
	xTry=$(( xLoc + 2*${deltaX[i]} ))
	yTry=$(( yLoc + 2*${deltaY[i]} ))
	if ((xTry > 0)) && ((xTry < width)) && ((yTry > 0)) && ((yTry<height)); then
	    if [[ ${theMap[yTry*width+xTry]} = '#' ]]; then
		dirs+=($i)
	    fi
	fi
    done
    # If there are more than one direction we can choose, remember this location for later
    # when we get stuck, we unwind the stack.  When the stack is empty, we are done
    if (( ${#dirs[@]}>1 )); then
	push
    fi
}

width=41
height=21

theMap=()
xStack=()
yStack=()

for ((y=0; y<height; y++)); do
    for ((x=0; x<width; x++)); do
	theMap[y*width+x]='#'
    done
done

xLoc=1
yLoc=1

makeHole
getDirs
while (( ${#xStack[@]} > 0 )); do
    if (( ${#dirs[@]}>0 )); then
	dir=${dirs[(($RANDOM%${#dirs[@]}))]}
	(( xLoc+=${deltaX[dir]} ))
	(( yLoc+=${deltaY[dir]} ))
	makeHole
	(( xLoc+=${deltaX[dir]} ))
	(( yLoc+=${deltaY[dir]} ))
	makeHole
    else
	pop
    fi
    getDirs
done

# make an enterance and an exit
xLoc=$(( RANDOM%width/2 ))
xLoc=$(( xLoc*2+1 ))
yLoc=0
makeHole
xLoc=$(( RANDOM%width/2 ))
xLoc=$(( xLoc*2+1 ))
yLoc=$(( height-1 ))
makeHole

# Print the maze.
for ((y=0; y<height; y++)); do
    printf "\n" 
    for ((x=0; x<width; x++)); do
	printf "%s" "${theMap[y*width+x]}"
	printf "%s" "${theMap[y*width+x]}"
    done
    printf "\n" 
    for ((x=0; x<width; x++)); do
	printf "%s" "${theMap[y*width+x]}"
	printf "%s" "${theMap[y*width+x]}"
    done
done
printf "\n"

Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#3188 Today 03:51:58

vicentereyes
Member
Registered: 2017-02-17
Posts: 5

Re: Post your handy self made command line utilities

Hi

I like trying out new and cool things from "the linux world" so I end up installing lots of packages and never remember to delete them. I don't really know why I care about that but it kinda feels wrong to have so much stuff installed.

So I read a bit of the AWK book (strongly recommended) and made this thing:

#!/usr/bin/gawk -f

BEGIN {
    # make array of regexes for recognizing package managers
    Managers[1] = "sudo pacman"
    Managers[2] = "(sudo )?yay"
    Managers[3] = "(sudo )?pacaur"
}

function IsInstalling(histLine) {
    for (i = 1; i <= length(Managers); i++) {
        if (histLine ~ Managers[i] " -S[yu]* ") {
            return 1 # True
        }
    }
    return 0 # False
}

function IsGrouped(histLine) {
    return histLine ~ "# *[-_a-zA-Z0-9]+ *$"
}

function IsUninstalling(histLine) {
    for (i = 1; i <= length(Managers); i++) {
        if (histLine ~ Managers[i] " -R") {
            return 1 # True
        }
    }
    return 0 # False
}

# can't return array, so it must be passed as a parameter then filled
function PackageNames(histLine, result) {
    # empty the result array to avoid problems
    for (i in result) {
        delete result[i]
    }

    b = 0
    for (i = 2; i <= NF; i++) {
        if (b && $i !~ "^[-#]") {
            result[$i] = "You should not see this"
        } else if (!b && $i ~ "^-") {
            b = 1
        } else if ($i ~ "^#") {
            return
        }
    }
}

IsInstalling($0) && IsGrouped($0) {
    PackageNames($0, result)
    for (package in result) {
        Groups[$NF][package] = "You shouldn't see this either"
    }
}

IsUninstalling($0) {
    PackageNames($0, result)

    for (group in Groups) {
        for (uninstalled in result) {
            if (uninstalled in Groups[group]) {
                delete Groups[group][uninstalled]
            }
        }
    }
}

END {
    for (group in Groups) {
        print "group name: " group
        for (package in Groups[group]) {
            print package
        }
        print ""
    }
}

Usage examples: whenever I want to install some things and remember to uninstall them if I want to,

yay install mpd ncmpcpp mpc # mpd
yay install rustc rust-racer # rust-dev

Then, to clean my system, a

history | awk -f thisfile

tells me what groups of packages I have made and what packages they have.

There are probably lots of improvements to be made, but I'm not much of an AWK wizard. (And I think the better choice would have been Perl anyway).

Offline

#3189 Today 10:41:25

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

Re: Post your handy self made command line utilities

vicentereyes, the biggest issue would be that 'history' is limited both in having a finite length and in having a scope of the current shell.  But every package installed is logged in pacman's log which would be a far better target and would need very little processing by awk/perl/etc.  For example, I think the following starting point would have about the same result:

sed -n 's/.*pacman -S[^ ]* \([a-zA-Z0-9].*\).$/\1/p' /var/log/pacman.log

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

Offline

Board footer

Powered by FluxBB