You are not logged in.

#1876 2012-08-05 16:02:46

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 20,200

Re: Post your handy self made command line utilities

Barrucadu wrote:

I switched over to systemd yesterday, and one of the things I was doing with inittab was automatically logging in to tty2. Well, I modified the getty@.service file for autologin purposes, and today I wrote a little script to manage which gettys are started and which auto-login.

Nice smile

You should consider packaging that one and putting it in the AUR.


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

#1877 2012-08-06 17:12:02

Silencement
Member
From: France
Registered: 2012-08-06
Posts: 12

Re: Post your handy self made command line utilities

I made this script this morning, it downloads wallpapers from Simple Desktops. I could download them all by hand but there are over a thousand pictures, and it would take a bit too long.
This script can do the following :

  • Downloads several pages of wallpapapers (a page = 28 wallpapers)

  • Does not download a wallpaper if it is already present in the target directory (or a sub directory)

  • Update mode : stops downloading when a wallpaper you already have is reached

  • Automatically stops when an empty page is reached

  • Name the PNG file according to the name it has on Simple Desktops

You use it like this :

bash simpledesktops.sh folder pages mode

"folder" is the destination directory.
"pages" is the number of pages to download (from 1 to the value you entered) or an interval of pages (like 3-6).
"mode" is an optional parameter, it can take three values :

  • normal (default), downloads every wallpaper from the pages you chose, and does not download wallpapers you already have

  • update : downloads the latest wallpapers, and stops when it reaches a wallpaper you already have

  • replace : downloads every wallpaper from the pages you chose and downloads wallpaper you already have

And here is the actual script :

#!/bin/bash
# Simple Desktops Mass Downloader

# Parsing parameters
if [[ $# < 2 ]]; then
	echo "Usage: simpledesktops.sh <destination> <pages> [<normal|update|replace>]"
	exit
fi

destination=$1
if [ ! -d "$destination" ]; then
	mkdir "$destination"
fi

pageseq=$2
if [ -z $(echo "$pageseq" | grep -) ]; then
	pageseq="1 $pageseq"
else
	pageseq=${pageseq/-/ }
fi

if [[ $# > 2 ]]; then
mode=$3
else
	mode="normal"
fi

# Main loop
updated=false
total=0
for pagenum in `seq $pageseq`
do
	echo "Fetching links from page $pagenum..."
	page=$(curl -s "http://simpledesktops.com/browse/$pagenum/" --compress | grep "295x184_q100.png")
	urls=$(echo "$page" | sed -r 's/(.+)src="(.+)\.295x184_q100.png(.+)/\2/')
	titles=$(echo "$page" | sed -r 's/(.+)title="(.+)" alt="(.+)/\2/')
	imgcount=$(echo "$titles" | wc -l)
	echo "Page $pagenum contains $imgcount images."

	# Checking for already existing images
	if [ $mode == "replace" ]; then
		titlestodl=$titles
		urlstodl=$urls
	else
		urlstodl=""
		titlestodl=""
		for img in `seq 1 $imgcount`
		do
			currenturl=$(echo "$urls" | head -n $img | tail -n 1)
			currenttitle=$(echo "$titles" | head -n $img | tail -n 1)

			if [[ -z $(find "$destination" | grep "/$currenttitle.png") ]]; then
				urlstodl="$urlstodl
				$currenturl"
				titlestodl="$titlestodl
				$currenttitle"
			else
				echo "$currenttitle already exists."
				if [ $mode == "update" ]; then
					updated=true
					break
				fi
			fi
		done
	fi
	titlestodl=$(echo "$titlestodl" | sed -r 's/^[\t]*//' | sed -r '/^[\t]*$/d')
	urlstodl=$(echo "$urlstodl" | sed -r 's/^[\t]*//' | sed -r '/^[\t]*$/d')
	todlcount=$(echo "$titlestodl" | wc -l)

	# Downloading images
	if [ $todlcount == 0 ]; then
		echo "No images to download from page $pagenum."
	else
		echo "Downloading $todlcount images from page $pagenum..."
		for img in `seq 1 $todlcount`
		do
			currenturl=$(echo "$urlstodl" | head -n $img | tail -n 1)
			currenttitle=$(echo "$titlestodl" | head -n $img | tail -n 1)
			if [[ $currenttitle != "" ]]; then
				echo "($img/$todlcount) $currenttitle..."
				curl -o "/tmp/$currenttitle.png" -# $currenturl
				mv "/tmp/$currenttitle.png" "$destination/$currenttitle.png"
				total=$(expr $total + 1)
			fi
		done
	fi

	if [ $updated == true ]; then
		echo "Done updating. There is $total new images in $destination."
		exit
	fi
done

# Shit happens
if [ -f "$destination/.png" ]; then
	rm "$destination/.png"
fi

echo "Finished downloading $total images from $pageseq pages in $destination."

I am pretty sure there is a better and cleaner way to do that, but it works perfectly so I have no reason to change it.

Last edited by Silencement (2012-08-06 19:24:16)


Derpy Hooves is best pony.

Offline

#1878 2012-08-06 18:25:25

sujoy
Member
From: Finland
Registered: 2008-02-08
Posts: 95

Re: Post your handy self made command line utilities

@Silencement

Nice app. Works beautifully. smile

Offline

#1879 2012-08-06 23:35:13

Awebb
Member
Registered: 2010-05-06
Posts: 6,602

Re: Post your handy self made command line utilities

#!/bin/bash

case "$1" in
		""|--help|-h)
				printf "Ask google in your default XDG browser.\nUsage: google [query]\ngoogle --help,-h: This help.\nUse quotes for multiple words."
				;;
		*)
				xdg-open "https://www.google.de/#hl=de&safe=off&output=search&q=$1"
				;;
esac

It's nothing fancy, but I just discovered, that xdg-open actually has it's reason to exist.

Offline

#1880 2012-08-07 04:42:40

marinftw
Member
Registered: 2009-12-13
Posts: 9

Re: Post your handy self made command line utilities

Well, this is my first "big" script, I'm still a newbie on bash programming but I really like it! any feedback about this could be very useful.
I use this to save a lot of time when someone request a new  web account on my Archlinux rackspace cloud server, I called it Simple Web Manager:

SWM can perform:

1.-Add Website. (Status=OK)
2.-Delete Website.(Status=Bad)
3.-Create Database.(Status=OK)
4.-Create Database_user.(Status=OK)
5.-Manage database_user permissions.(Status=limited)

#!/bin/bash

##########################################################
#                                                        #
#                SIMPLE WEB MANAGER                      #
#                                                        #
#                BY: Marin Alcaraz                       #
#                 V:1.0  LU:01/08/12                     #
#                                                        #
#   Simple web manager provides an easy way to           #
#   manage apache2 virtual hosts, manage users           #
#   and databases on archlinux.                          #
#   Apache virtual host must be enabled.                 #
#                                                        #
#    The content of this file is licensed under          #
#    the MIT license.                                    #
#                                                        #
##########################################################


#General Info

VERSION="Version 1"
INFO="Simple Web Manager $VERSION "
BASE_PATH="/home"
VHOST_PATH="/etc/httpd/conf/extra/httpd-vhosts.conf"
MYSQL=`which mysql`

echo -e "$INFO \n"

#Menu
PS3='Please Select an option '

options=("Add Account" "Delete Account" "Create Database" "Create Database_User" "Manage DB_user permissons" "Quit")
select opt in "${options[@]}"
   
do
        case $opt in
            "Add Account")
                #Request account name and creates it
                
                read -p "Give an account: " ACCOUNT
                adduser $ACCOUNT
                cut -d: -f1 /etc/passwd | grep "$ACCOUNT" > /dev/null
                ST=$?
                if [ $ST -eq 0 ]
                then
                    mkdir -p $BASE_PATH/$ACCOUNT/{public_html,private,logs,cgi-bin,backup} 
                    chmod -R 755 $BASE_PATH/$ACCOUNT
                    read -p "Give a domain: " DOMAIN
                    
                    VHOST_DEFINITION="
                                <VirtualHost *:80>
                                    \n  ServerAdmin dontbother@me.com
                                    \n DocumentRoot /home/$ACCOUNT/public_html
                                    \n ServerName $DOMAIN
                                    \n ServerAlias www.$DOMAIN
                                    \n ErrorLog /home/$ACCOUNT/logs/$DOMAIN-error_log
                               \n </VirtualHost>"

                    echo -e $VHOST_DEFINITION >> $VHOST_PATH
                    rc.d restart httpd
                    echo -e "ACCOUNT $ACCOUNT SUCCESFULLY CREATED \n"
                else
                 echo "hi"    
                fi
                
                ;;

            "Delete Account")
                read -p "Give an account: " ACCOUNT
                read -p "Are you sure?? (1,0) You are attempting to delete  $BASE_PATH/$ACCOUNT/  and all it's content" CONF
                if [ $CONF -eq 1 ]
                then
                    userdel $ACCOUNT
                    rm -rf $BASE_PATH/$ACCOUNT/
                    echo "Account Succesfully Deleted"
                else
                    echo "There was an errorer deleting the account: $ACCOUNT"
                fi
                ;;

             "Create Database")
                read -p "Database name: " DBNAME
                echo "Create Database"
                    QUERY1="CREATE DATABASE IF NOT EXISTS $DBNAME"
                    $MYSQL -u root -p -e "$QUERY1"
                ;;

            "Create Database_User")
                echo "Create Database_User"
                read -p "Database user name: " DBUSER
                    QUERY2="CREATE USER $DBUSER"
                    $MYSQL -u root -p -e "$QUERY2"
                ;;

            "Manage DB_user permissons")
                echo "Manage DB_user permissons"
                read -p "User name: " DBUSER
                read -p "Set mysql pass: " MSPASS
                read -p "Database: " MSDB

                QUERY3="GRANT ALL ON $MSDB.* TO '$DBUSER'@'localhost' IDENTIFIED BY '$MSPASS'; FLUSH PRIVILEGES;"
                $MYSQL -u root -p -e "$QUERY3"
                ;;

            "Quit")
                break
                ;;
            *) echo "invalid option";;
        esac
done

Again I'm a newbie so any feedback about any topic involving this script would be great, it stills on early development phase but it can add users and make the database jobs without any problem, the option that I don't recommend to use it's delete user, and the privilege database it's only able to grant all privileges on the selected database, I hope it will get better in the future. Rackspace DNS tool manage the domain redirection.

There is a wiki on my github account.

Thank you guys, hope you like it.

Offline

#1881 2012-08-07 13:31:54

derhil
Member
Registered: 2012-04-04
Posts: 10

Re: Post your handy self made command line utilities

Slightly modified version of https://bbs.archlinux.org/viewtopic.php … 2#p1136222



http://files.derhil.de/screenshot/sysinfo.png

#/bin/bash

clear

echo -e "\e[34m
   _____                .__      .____    .__
  /  _  \_______   ____ |  |__   |    |   |__| ____  __ _____  ___
 /  /_\  \_  __ \_/ ___\|  |  \  |    |   |  |/    \|  |  \  \/  /
/    |    \  | \/\  \___|   Y  \ |    |___|  |   |  \  |  />    <
\____|__  /__|    \___  >___|  / |_______ \__|___|  /____//__/\_ \\
        \/            \/     \/          \/       \/            \/       
\e[0m"

# UPTIME
awk '// {
	sec = int($1)
	days = int(sec/3600/24)
	sec -= days*24*3600
	hours = int(sec/3600)
	sec -= hours*3600
	mins = int(sec/60)
	sec -= mins*60
	secs = int(sec)
	printf "\033[1;32mUptime\033[0m:   %i days, %ih %im %is\n",
		days, hours, mins, secs;
}' /proc/uptime

# Kernel
awk '// {printf "\033[1;32mKernel\033[0m:   %s\n", $3}' /proc/version

# Hostname
awk '// {printf "\033[1;32mHostname\033[0m: %s\n", $1}' /proc/sys/kernel/hostname

# CPU
awk '/^model name/ {
	print "\033[1;32mCPU\033[0m:     ",$4,$5,$6,$7,$8;
	exit;
}' /proc/cpuinfo


# MEM USE:
awk '
/Mem:/ { total=$2; }
/cache:/ {
	printf "\033[1;32mRAM\033[0m:      %i MB / %i MB (\033[0;33m%i\033[0m%)\n",
		$3, total, $3*100/total;
}' <(free -m)


# DISK USE:
awk '
/root/ {
	printf "\033[1;32mROOT\033[0m:     %.1f GB / %.1f GB (\033[0;33m%i\033[0m%) (%s)\n",
		$4/1000000,$3/1000000,$4*100/$3,$2;
}
/home/ {
	printf "\033[1;32mHOME\033[0m:     %.1f GB / %.1f GB (\033[0;33m%i\033[0m%) (%s)\n",
		$4/1000000,$3/1000000,$4*100/$3,$2;
}' <(/bin/df -T)


# GTK THEME:
if test -f $HOME/.gtkrc-2.0;then
	GTK=$HOME/.gtkrc-3.0
	[[ -f $HOME/.gtkrc-2.0 ]] && GTK=$HOME/.gtkrc-2.0
	awk -F '="|"' '
	/gtk-theme-name/ {printf "\033[1;32mTheme\033[0m:    %s\n", $2}
	/gtk-icon-theme-name/ {printf "\033[1;32mIcons\033[0m:    %s\n", $2}
	/gtk-font-name/	{printf "\033[1;32mFont\033[0m:     %s\n\n", $2}
	' $GTK 
else
	echo -e "\e[1;32mTheme\033[0m:    -"
	echo -e "\e[1;32mIcons\033[0m:    -"
	echo -e "\e[1;32mFont\033[0m:     -\n"
fi

# COLORS:
echo -e "\e[1;32mColors\e[0m:\n\e[0;30m###### \e[0;31m###### \e[0;32m###### \e[0;33m###### \e[0;34m###### \e[0;35m###### \e[0;36m###### \e[0;37m######\e[0m\n\e[1;30m###### \e[1;31m###### \e[1;32m###### \e[1;33m###### \e[1;34m###### \e[1;35m###### \e[1;36m###### \e[1;37m######\e[0m\n"

Last edited by jasonwryan (2012-08-07 17:50:19)

Offline

#1882 2012-08-07 19:17:55

Roken
Member
From: South Wales, UK
Registered: 2012-01-16
Posts: 1,281

Re: Post your handy self made command line utilities

My own variation of the system info script, designed to mimic archey but without the first run delay (I don't report installed packages because it causes the delay the first time it's run, and since I use this in bashrc, that's a PITA:

Thanks to derhill - I nicked your UPTIME bit smile

#!/bin/bash

#Window/Display manager

if [ ! -z $DISPLAY ]; then
	WM_WINDOW=$(xprop -root _NET_SUPPORTING_WM_CHECK)
	WM_WINDOW=${WM_WINDOW##* }
	WM_NAME=$(xprop -id $WM_WINDOW 8s _NET_WM_NAME)
	WM_NAME=${WM_NAME##* }
	WM_NAME=`echo $WM_NAME | sed 's/\"//g'`
	DM_NAME=`ps -ef | grep dm | grep "\-nodaemon" | awk '{print $8}'| sed 's/.*\///g' | sed 's/-.*//'`
else
	WM_NAME=""
	DM_NAME=""
fi

booted=`awk '// {
	sec = int($1)
	days = int(sec/3600/24)
	sec -= days*24*3600
	hours = int(sec/3600)
	sec -= hours*3600
	mins = int(sec/60)
	sec -= mins*60
	secs = int(sec)
	printf "%i days, %i:%i:%i",days, hours, mins, secs;
	}' /proc/uptime`

echo -e "$(tput setaf 6)               +                "
echo -e "$(tput setaf 6)               #                "
echo -e "$(tput setaf 6)              ###               "
echo -e "$(tput setaf 6)             #####              "
echo -e "$(tput setaf 6)             ######             "
echo -e "$(tput setaf 6)            ; #####;            User: $(tput setaf 7)"$USER
echo -e "$(tput setaf 6)           +##.#####            Hostname: $(tput setaf 7)"$HOSTNAME
echo -e "$(tput setaf 6)          +##########           Distro: $(tput setaf 7)"`lsb_release -d | sed 's/Description:[^A-Za-z]//'`
echo -e "$(tput setaf 6)         #######$(tput setaf 4)####$(tput setaf 6)##;         Kernel: $(tput setaf 7)"`uname -r`
echo -e "$(tput setaf 6)        ###$(tput setaf 4)############+$(tput setaf 6)        Uptime: $(tput setaf 7)"$booted
echo -e "$(tput setaf 6)       #$(tput setaf 4)######   #######$(tput setaf 6)        Window Manager: $(tput setaf 7)"$WM_NAME
echo -e "$(tput setaf 4)     .######;     ;####;'.      $(tput setaf 6)Desktop Environment: $(tput setaf 7)"$DESKTOP_SESSION
echo -e "$(tput setaf 4)    .#######;     ;#####.       $(tput setaf 6)Shell: $(tput setaf 7)"$SHELL
echo -e "$(tput setaf 4)    #########.   .########'     $(tput setaf 6)Terminal: $(tput setaf 7)"$TERM
echo -e "$(tput setaf 4)   ######'           '######    $(tput setaf 6)Display Manager: $(tput setaf 7)"$DM_NAME
#Packages: $(tput setaf 7)`pacman -Qqi | grep Name | grep -c '[^[:space:]]'`
echo -e "$(tput setaf 4)  ;####                 ####;   $(tput setaf 6)CPU: $(tput setaf 7)"`cat /proc/cpuinfo | grep "model name" | sed 's/^.*: //' | head -n 1`
echo -e "$(tput setaf 4)  ##'                     '##   $(tput setaf 6)RAM: $(tput setaf 2)"`free -h | grep Mem: | awk '{print $3}'` "$(tput setaf 1)/" `free -h | grep Mem: | awk '{print $2}'`
echo -e "$(tput setaf 4) #'                         '#  $(tput setaf 6)Disk: $(tput setaf 2)"`df --total -h | grep total | awk '{print $3}'` "$(tput setaf 1)/" `df --total -h | grep total | awk '{print $2}'`

Last edited by Roken (2012-08-11 10:28:34)


Ryzen 5900X 12 core/24 thread - RTX 3090 FE 24 Gb, Asus Prime B450 Plus, 32Gb Corsair DDR4, Cooler Master N300 chassis, 5 HD (1 NvME PCI, 4SSD) + 1 x optical.
Linux user #545703

/ is the root of all problems.

Offline

#1883 2012-08-09 23:59:27

madprops
Member
Registered: 2012-05-26
Posts: 26

Re: Post your handy self made command line utilities

suspender
---------------
suspend the computer after a certain percentage of battery remaining is met.
usage: suspender [number] or without arguments for interactive mode.

#!/usr/bin/python

import os
import re
import sys
import time
import subprocess

min = 10

try:
	if len(sys.argv) < 2:
			imin = input('suspend at  what percentage of battery remaining (default 10): ')
			if imin != '':
				min = int(imin)
	else:
		min = int(sys.argv[1])
except:
	sys.exit('wrong arguments')

print('computer will suspend at ' + str(min) + '% of battery remaining...')

try:
	while True:
		(acpi, err) = subprocess.Popen('acpi', stdout=subprocess.PIPE, shell=True).communicate()
		try:
			bat = int(re.compile(r"[0-9]{2}%+").findall(str(acpi))[0][:2])
		except IndexError:
			bat = int(re.compile(r"[0-9]{1}%+").findall(str(acpi))[0][:1])
		print(str(bat) + '% of battery remaining')
		if bat <= min:
			break
		time.sleep(60)
	print('suspending...')
	os.system('pm-suspend')
except KeyboardInterrupt:
	print()
	pass

Last edited by madprops (2012-08-10 00:05:07)

Offline

#1884 2012-08-10 00:17:59

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

Re: Post your handy self made command line utilities

An evolution of me using mplayer as a mp3 player and trying to have some control over the output...

#!/bin/bash
# Use mplayer to play mp3 and
# tail to find tag info and colourise
# the output
# usage : bliss <path>
# where path is to a directory of mp3's
#
# Set some colours

INFO='\e[38;05;226m'
SONG='\e[38;05;172m'
ARTIST='\e[38;05;113m'
ALBUM='\e[38;05;137m'
HEADER='\e[38;05;242m'
BG='\e[48;05;236m'
HIDE_CURSOR='\e[?25l'
SHOW_CURSOR='\e[?25h'
# for spacing right align text
width=`printf "%20s" " "` # twenty spaces

## With mplayer running Ctrl+c won't exit, just goes through
## the while loop again so trap it and show the cursor again
trap 'printf "${INFO}EXITING $SHOW_CURSOR";exit 0' INT
clear

# If no path to a diectory of mp3's is given use a default
if [ -z "$1" ]; then
    music_folder=~/Favs
else
    music_folder="$1"
fi

# check for a playlist file or add one randomising the order
if [ ! -e "$music_folder/playlist.txt" ]; then
    printf "$INFO Making Playlist from $SONG$music_folder ${INFO}folder\n\n"
    while read line; do
	    [[ $line = *mp3 ]] || continue
	    echo "$RANDOM $line";
    done < <(ls "$music_folder") | sort | sed -r 's/^[0-9]+ //' > "$music_folder"/playlist.txt
fi
count=`wc -l "$music_folder"/playlist.txt | awk '{print $1}'`
printf "$HEADER${width:5}TITLE ${width:6}ARTIST ${width:5}ALBUM\n"
# loop through the directory in random order
while true; do
    #clear
    num=$(($RANDOM%$count))
    [[ $num -ne oldnum ]] || continue
    filename=`awk -v awk_num=$num 'NR==awk_num { print; exit }' "$music_folder"/playlist.txt`

    [[ -e "$music_folder/$filename" ]] || continue
    title=`tail -c 125 "$music_folder/$filename" 2> /dev/null | head -c 30`
    artist=`tail -c 95 "$music_folder/$filename" 2> /dev/null | head -c 30`
    album=`tail -c 65 "$music_folder/$filename" 2> /dev/null | head -c 30`
    printf "\r\e[K$HIDE_CURSOR$SONG$BG${width:${#title}}$title $ARTIST${width:${#artist}}$artist $ALBUM${width:${#album}}$album \e[0m" 2> /dev/null
    mplayer -ao alsa "$music_folder/$filename" 2>&1 > /dev/null
    oldnum=$num
done
exit 0
# "${width:0:${#x}}$x"

Last edited by moetunes (2012-08-10 19:37:17)


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

Offline

#1885 2012-08-10 16:40:32

Ikem
Member
Registered: 2012-08-10
Posts: 10
Website

Re: Post your handy self made command line utilities

That's some of the scripts I wrote:

* gtkparasite
* openbox-theme-switcher
* startxephyr
* xdg-exec

Offline

#1886 2012-08-11 06:29:09

debdj
Member
Registered: 2012-01-19
Posts: 163

Re: Post your handy self made command line utilities

It generally doesn't make sense to implement some sorting algorithm in a bash script, but I did this just for fun. big_smile Albeit its lot slower than if implemented in C.
It does a insertion sort which depends on a binary search to find the right place to insert the value.

The read builtin can probably take no more than 4096 characters though stdin. I can sort around 910 - 950 random numbers in around 3secs, but of course that depends upon the data set.
I once tried sorting a file of 100,098 numbers, that was taking too long to let it continue. big_smile

#!/bin/bash

read -p "Enter: " -a arr
items=${#arr[@]}

for (( i=1; i<$items; i=$[i+1] )); do

key=${arr[$i]}
#bin_srch "${arr[@]}" $key $i

lb=0; ub=$i

while [ $lb -lt $ub -o $lb -eq $ub ]; do    #start a binary search
pos=
mid=$[lb+((ub-lb)/2)]

[[ $key -eq ${arr[$mid]} ]] && { pos=$mid && break; }

if [[ $key -gt ${arr[$mid]} ]]; then
lb=$[mid+1]
elif [[ $key -lt ${arr[$mid]} ]]; then
ub=$[mid-1]
fi

done           #end binary search

[[ -z $pos ]] && pos=$lb  # if value isn't found return the lower bound reached

for (( j=$[i-1]; $j>=$pos; j=$[j-1] )); do

  arr[$[j+1]]=${arr[$j]}   # shift through the array
#[[ $1 = '-v' ]] && echo ${arr[@]}
done

arr[$pos]=$key  #insert

done

#[[ $1 = '-v' ]] && echo -e "${arr[@]} : insert\n"

echo -e "\nSorted: ${arr[@]}\n"

Last edited by debdj (2012-08-11 06:29:24)

Offline

#1887 2012-08-11 09:21:25

Cloudef
Member
Registered: 2010-10-12
Posts: 636

Re: Post your handy self made command line utilities

@debdj

#!/bin/bash
function f() {
    sleep "$1"
    echo "$1"
}
while [ -n "$1" ]
do
    f "$1" &
    shift
done
wait

./sort 5 6 4 1 3

Offline

#1888 2012-08-11 13:11:55

Ikem
Member
Registered: 2012-08-10
Posts: 10
Website

Re: Post your handy self made command line utilities

Cloudef wrote:

./sort 5 6 4 1 3

I don't really get how that works..

And I noticed, the bigger the numbers, the slower it becomes.

Offline

#1889 2012-08-11 13:55:13

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

Ikem wrote:
Cloudef wrote:

./sort 5 6 4 1 3

I don't really get how that works..

Not sure what you're asking about. 'sort' is the name of the script.

Ikem wrote:

And I noticed, the bigger the numbers, the slower it becomes.

True. Just try e.g. '5 7 2 1 99 8 4 5' The two 5's will be printed immediately one after another while you'll have to wait a bit for '99' to appear after '8' :-)

Offline

#1890 2012-08-11 16:03:47

sujoy
Member
From: Finland
Registered: 2008-02-08
Posts: 95

Re: Post your handy self made command line utilities

ha ha, nice idea,
sleep as long as the value and then print the value.
effectively sorting the number, if the list isn't too long.

sleep is the reason large numbers take time to print. tongue

Offline

#1891 2012-08-11 17:01:24

grufo
Member
Registered: 2012-08-09
Posts: 100

Re: Post your handy self made command line utilities

https://bbs.archlinux.org/viewtopic.php?id=146850 smile

"A simple but well coloured feed reader written in bash"

Last edited by grufo (2012-08-11 17:01:52)

Offline

#1892 2012-08-11 21:30:40

Ikem
Member
Registered: 2012-08-10
Posts: 10
Website

Re: Post your handy self made command line utilities

karol wrote:

Not sure what you're asking about.

How does that script sort the numbers? What's the logic behind it?

Offline

#1893 2012-08-11 21:37:34

Cloudef
Member
Registered: 2010-10-12
Posts: 636

Re: Post your handy self made command line utilities

Ikem wrote:
karol wrote:

Not sure what you're asking about.

How does that script sort the numbers? What's the logic behind it?

It forks process which first sleeps for the number given and then echos it, for each argument.
You can make it faster by dividing the number for the sleep command, however this will need a sleep with floating point support.
(Some embedded sleep implementations don't have such support eg. busybox I think.)

Also it's not my idea, google 'Sleep sort' to see the original.

Last edited by Cloudef (2012-08-11 21:38:00)

Offline

#1894 2012-08-12 06:56:05

debdj
Member
Registered: 2012-01-19
Posts: 163

Re: Post your handy self made command line utilities

@cloudef thats clever big_smile
But I cant ask it to sort some large numbers and go sleep myself tongue

Last edited by debdj (2012-08-12 10:43:13)

Offline

#1895 2012-08-12 12:20:56

Ikem
Member
Registered: 2012-08-10
Posts: 10
Website

Re: Post your handy self made command line utilities

Yeah. I agree. It's pretty clever. And thanks for the explanation.

Offline

#1896 2012-08-23 22:35:46

burninate
Member
Registered: 2012-07-28
Posts: 22

Re: Post your handy self made command line utilities

I made this little function in bash using the esoteric bash builtin select so that finding and browsing man pages is done easier in one action :

 # search and browse manpages interactively
function apr {
    err="usage: $FUNCNAME [object]"
    test $# -ne 1 && echo $err && return 1

    IFS=$'\n' manpgs=( $(apropos $1 | grep ^$1) )
    select line in ${manpgs[@]}; do
        n=${line%%) *}; n=${n#* (}
        man ${n} ${line%% *}
        break
    done
}

Edit: removed redundant $manpg line
Edit2: added a break statement for convenience (Trilby)

Last edited by burninate (2012-08-25 10:15:27)

Offline

#1897 2012-08-24 01:36:35

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

Re: Post your handy self made command line utilities

burninate that's awesome.  Here's a dumb question though, I end up in a loop: I select a man page, "q" to leave the man page, then am asked for another selection.  Is there a way to quit other than Ctrl-C?

In an attempt to figure this out myself I tried to read man select ... and the first man page was the wrong page.  So I used this function to learn about select itself - but the bash select function doesn't seem to have a man page.  Could you point me to some relevant links/reading material?  Thanks. Well, of course google can take care of that last part.

I think I'll use a different function name.  It's like "man", but more elegant and well organized.  I shall call it "woman".  smile

Edit: A search gave me this link which answers my questions ... so just consider this post a thank you for a new learning oportunity.

Last edited by Trilby (2012-08-24 01:41:40)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#1898 2012-08-24 09:20:21

burninate
Member
Registered: 2012-07-28
Posts: 22

Re: Post your handy self made command line utilities

@Trilby
Thank you. I usually just hit Ctrl-D to exit select loops. If you want (and perhaps more user friendly) you can include a choice for exiting in the select list like N) exit where N is the first/last item. Something like this should work:

function apr {
...
    select line in ${manpgs[@]} exit; do
        if [ $line == exit ]; then
            return;
        fi
        n=${line%%) *}; n=${n#* (}
        man ${n} ${line%% *}
    done
}

Or add a break statement after the man statement.

Last edited by burninate (2012-08-25 10:13:54)

Offline

#1899 2012-08-24 12:03:08

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

Re: Post your handy self made command line utilities

Thanks, I just added a break at the end of the select block.  I only get one choice - but I like this as a default.  If I want to view  another page I can just hit <UP-ARROW> <ENTER> to reissue the command.


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#1900 2012-08-24 15:56:05

wuyingren
Member
From: Catalunya
Registered: 2009-03-18
Posts: 8
Website

Re: Post your handy self made command line utilities

Another little script. This one counts lines from a text file (if it's from a DOS/Windows environment use dos2unix first, the script does not detect CRLF). It outputs total number of lines, number of blank lines and number of lines with text. Needed for a little project : )

It takes one argument, the path to the text file. Enjoy!

#!/bin/bash

count=0
total=0
wtext=0

while read line
do
 let total=total+1
 
 if [ -z "$line" ]; then
        let count=count+1
 fi

done < $1

let wtext=total-count

echo "$total lines on $1"
echo "$count blank lines on $1"
echo "$wtext lines with text on $1"

Offline

Board footer

Powered by FluxBB