speeding up scripts

For discussions about programming, programming questions/advice, and projects that don't really have anything to do with Puppy.
Message
Author
User avatar
technosaurus
Posts: 4853
Joined: Mon 19 May 2008, 01:24
Location: Blue Springs, MO
Contact:

#16 Post by technosaurus »

I just wanted to mention that almost all of the external binary advice goes out the window if you use a busybox shell (ash/hush) with the busybox_prefer_applets option enabled. No major x86 distro, with the exception of maybe alpine linux, enables it by default though.

here is a template that I use to parse desktop files

Code: Select all

#!/bin/ash
#Copywrong 2011 Brad Conroy - released to the public domain
#Parse through the .desktop files, generate use{ful,less} output
#Though they have Var=value structure, we cannot source them directly (damn) because:
#1. many Vars have illegal characters ... but not the ones we actually want (for now - see TODO)
#2. many values have spaces
#Solution
#1. grep for only the fields that we want to eliminate problem #1
#2.(a) use sed to put quotes after the = and at the end of the line to accomodate spaces
#2.(b) ayttm (possibly others) has a non-standard set of quotes so add a sed for that (could tr -s '"',but sed is already called)
#But wait we didn't _actually_ modify the file, so we can't source it - what a waste of time
#That's ok, we can just use eval on a variable (or in this case a return) to do the same thing
#
#Ok now we have the values, but what to do with them?  We will just output them to an easily awkable file
#but writing to a file is slow, so store it in a Variable in-loop and write once out-of-loop
#... at this point you could instead add a single case statement to generate menu entries or anything useful
#TODO add parameters to the sed/grep parts to localize if available (trivial, but would complicate the demo)
for x in /usr/share/applications/* ; do
    eval `grep -E ^Name=\|^Categories=\|^Comment=\|^Icon= $x |sed "s/=/=\"/g ; s/$/\"/g ; s/\"\"/\"/g"`
    OUTPUT=${OUTPUT}${Name:-UNDEFINED}\|${Categories:-UNDEFINED}\|${Comment:-UNDEFINED}\|${Icon:-UNDEFINED}"\n"
done
echo -e $OUTPUT
Check out my [url=https://github.com/technosaurus]github repositories[/url]. I may eventually get around to updating my [url=http://bashismal.blogspot.com]blogspot[/url].

User avatar
technosaurus
Posts: 4853
Joined: Mon 19 May 2008, 01:24
Location: Blue Springs, MO
Contact:

#17 Post by technosaurus »

Code: Select all

#this time with fgrep, it needs newline separators and doesn't support "^" (beginning of line)
#This pulls in GenericName and other problem children ... just for demo, then back to grep -E or egrep
#... thus the 4th sed (a blank entry becomes ="$ so fix it)
#This time we will thread the parsing of each file - it is ~10x faster but borks sorting by *.desktop name
#perhaps we want to sort by app name or category ... or, if you are using bash, store them in an mxn array

String="Name=
Categories=
Comment=
Icon=
Exec=" 

parse(){ #by pulling this out of the main loop we can fork it with the & and run many simultaneously
eval $(fgrep "$String" ${1} |sed 's/=/=\"/g ; s/$/\"/g ; s/\"\"/\"/g ; s/=\"$/=\"\"/')
echo ${Name:-UNDEFINED}\|${Categories:-UNDEFINED}\|${Comment:-UNDEFINED}\|${Icon:-UNDEFINED}\|${Exec:-UNDEFINED}
}

printf "" > /tmp/file #start with a clean file
for x in /usr/share/applications/* ; do
 parse "${x}" 2>/dev/null >>/tmp/file &
done

#hmm the recursing of the files is done, but what about all of the threads?
#lets try sorting the file and see?
#sort file > ${1:-sortedfile}
#nope missing entries, need to wait ... but how long
#don't just make a sufficiently long sleep for _your_ box
#we will just wait for sed to complete

while (pidof sed >/dev/null) do
printf . #as long as sed is running print dots every 10 milliseconds
sleep 0.01
done
sort /tmp/file > ${1:-sortedfile}
Check out my [url=https://github.com/technosaurus]github repositories[/url]. I may eventually get around to updating my [url=http://bashismal.blogspot.com]blogspot[/url].

amigo
Posts: 2629
Joined: Mon 02 Apr 2007, 06:52

#18 Post by amigo »

"grep -F by default". Yeah that's okay. Of course it's an extra process since it's a wrapper. On my older Slack, fgrep is a *link* to grep. But ony my own kiss-linux I install the real binary of fgrep. It's a smaller bin so has less latency.

Techno's bit of code makes a good example. I compared it to a pure-shell solution which gives the same output:

Code: Select all

#/bin/bin/bsh
# this runs fine on 'real' ash and should work with bb ash
#/usr/bin/bsh
# It will also run using 'bsh' the 'real' Bourne shell
# Quite obvioulsy would run with any bash, as well.


#Copywrong 2011 Brad Conroy - released to the public domain 
#Parse through the .desktop files, generate use{ful,less} output 
#Though they have Var=value structure, we cannot source them directly (damn) because: 
#1. many Vars have illegal characters ... but not the ones we actually want (for now - see TODO) 
#2. many values have spaces 
#Solution 
#1. grep for only the fields that we want to eliminate problem #1 
#2.(a) use sed to put quotes after the = and at the end of the line to accomodate spaces 
#2.(b) ayttm (possibly others) has a non-standard set of quotes so add a sed for that (could tr -s '"',but sed is already called) 
#But wait we didn't _actually_ modify the file, so we can't source it - what a waste of time 
#That's ok, we can just use eval on a variable (or in this case a return) to do the same thing 
# 
#Ok now we have the values, but what to do with them?  We will just output them to an easily awkable file 
#but writing to a file is slow, so store it in a Variable in-loop and write once out-of-loop 
#... at this point you could instead add a single case statement to generate menu entries or anything useful 
#TODO add parameters to the sed/grep parts to localize if available (trivial, but would complicate the demo) 
function techno() {
for x in /usr/share/applications/* ; do 
    eval `grep -E ^Name=\|^Categories=\|^Comment=\|^Icon= $x |sed "s/=/=\"/g ; s/$/\"/g ; s/\"\"/\"/g"` 
    OUTPUT=${OUTPUT}${Name:-UNDEFINED}\|${Categories:-UNDEFINED}\|${Comment:-UNDEFINED}\|${Icon:-UNDEFINED}"\n" 
done 
echo -e $OUTPUT
}
#time techno
# On my 700mHz P-III the above runs in
#real    0m0.882s
#user    0m0.380s
#sys     0m0.430s
# on a dir with 56 items
# Hmm, that echo -e may not be enirely portable, but you could use printf or /bin/echo instead

#Copyright Gilbert Ashley <amigo@ibiblio.org>
amigo() {
> test.file
for DESKTOP_FILE in /usr/share/applications/* ; do
#for DESKTOP_FILE in /usr/share/applications/Editra.desktop ; do
	OUT=
	while read LINE ; do
		case $LINE in
			Name=*) NAME="${LINE#*=}"'|'  ;;
			Comment=*) OUT=$OUT"${LINE#*=}"'|'  ;;
			Icon=*) ICON="${LINE#*=}"'|'  ;;
			#Terminal=*)
			#Type=*)
			Categories=*) CATS="${LINE#*=}"'|'  ;;
			Exec=*) EXEC="${LINE#*=}"'|'  ;;
			#Comment=*) COMM="${LINE#*=}"  ;;
		esac
	done < $DESKTOP_FILE
	echo $NAME$ICON$CATS$EXEC
	# To test the extract function below, use the following line instead of above
	# echo $NAME$ICON$CATS$EXEC >> test.file
done
}

time amigo
# On my 700mHz P-III the above runs in
#real    0m0.160s
#user    0m0.130s
#sys     0m0.010s
# on a dir with 56 items

# And about 'awkable', there again we can do that with pure shell:
extract() {
while read LINE ; do
	# skip the line if NULL
	case $LINE in '') continue ;; esac
	
	# more conventional approaches awk:
	#echo $LINE | awk -F '|' '{ print $4 }'
	#real    0m0.684s
	#user    0m0.290s
	#sys     0m0.330s
	
	# and with cut:
	#echo "$LINE" |cut -f4 -d'|'
	#real    0m0.613s
	#user    0m0.200s
	#sys     0m0.350s

	( IFS='|' ; set ${LINE} ; echo $4 )
	# Using ash:
	#real    0m0.298s
	#user    0m0.070s
	#sys     0m0.170s
	# Using bash:
	#real    0m0.296s
	#user    0m0.080s
	#sys     0m0.120s
	# Using bsh:
	#real    0m0.285s
	#user    0m0.060s
	#sys     0m0.110s

done < test.file
}

time extract

Should run even faster using bb ash since it's all a single process. I'd point out, that even though you are using bb grep and sed(right?), you are still running a separate process for each one.

PANZERKOPF
Posts: 282
Joined: Wed 16 Dec 2009, 21:38
Location: Earth

#19 Post by PANZERKOPF »

technosaurus wrote: busybox_prefer_applets option enabled.
That is great option but seems we must mount /proc before using it.
After making this in sysinit:
/bin/busybox mount -t proc proc /proc
We can call any builtin application directly.
Is that right?
SUUM CUIQUE.

User avatar
technosaurus
Posts: 4853
Joined: Mon 19 May 2008, 01:24
Location: Blue Springs, MO
Contact:

#20 Post by technosaurus »

PANZERKOPF wrote:
technosaurus wrote: busybox_prefer_applets option enabled.
That is great option but seems we must mount /proc before using it.
After making this in sysinit:
/bin/busybox mount -t proc proc /proc
We can call any builtin application directly.
Is that right?
I don't know about _any_, but most (some _may_ need other stuff like sys/dev or specific files/nodes) however, if you have busybox ash or hush as /bin/sh and a shell-compliant-script relies on standard utils, it will fail ... you'd need to mod it from util <args> to /path/to/util <args> for those instances ... which is why no major distro is doing it
Check out my [url=https://github.com/technosaurus]github repositories[/url]. I may eventually get around to updating my [url=http://bashismal.blogspot.com]blogspot[/url].

User avatar
technosaurus
Posts: 4853
Joined: Mon 19 May 2008, 01:24
Location: Blue Springs, MO
Contact:

#21 Post by technosaurus »

Thanks to amigo for the read line trick.
I used it to throw together a jwm_menu_create script that completes in 1/15th the time of fixmenus using only shell commands (and one echo -e, because some of Puppy's busyboxes don't have printf)

usage:
jwm_menu_create > ${HOME}/.jwmrc && jwm -restart #by default it will just go to stdout

Todo:
1. What the heck is up the default*.desktop file stubs - do I need a work around or are they misplaced/malformed (they are missing most entries)
2. Localization - just needs another case statement, but few .desktop files support it anyways ... and my Locale is already default :)

Edit It is now in this thread
http://www.murga-linux.com/puppy/viewtopic.php?t=70804
Last edited by technosaurus on Tue 16 Aug 2011, 09:00, edited 1 time in total.
Check out my [url=https://github.com/technosaurus]github repositories[/url]. I may eventually get around to updating my [url=http://bashismal.blogspot.com]blogspot[/url].

amigo
Posts: 2629
Joined: Mon 02 Apr 2007, 06:52

#22 Post by amigo »

"1/15th the time of fixmenus" -Well, I guess it was worth the effort. One time I re-wrote something and it ran in 3% of the former time -even though neither routine used any externals.

jamesbond
Posts: 3433
Joined: Mon 26 Feb 2007, 05:02
Location: The Blue Marble

#23 Post by jamesbond »

Thanks, this is very educational. I don't use the jwm so the script isn't much help for me, but the idea behind it is very helpful for future projects.
Fatdog64 forum links: [url=http://murga-linux.com/puppy/viewtopic.php?t=117546]Latest version[/url] | [url=https://cutt.ly/ke8sn5H]Contributed packages[/url] | [url=https://cutt.ly/se8scrb]ISO builder[/url]

User avatar
sc0ttman
Posts: 2812
Joined: Wed 16 Sep 2009, 05:44
Location: UK

#24 Post by sc0ttman »

jamesbond wrote:Thanks, this is very educational.
Once again I started a thread I'm too thick to follow :lol: This thread went over my head about 2 pages ago.. I'm gonna read, re-read, and re-read again until it makes sense! But I'm still loving the results! :)
[b][url=https://bit.ly/2KjtxoD]Pkg[/url], [url=https://bit.ly/2U6dzxV]mdsh[/url], [url=https://bit.ly/2G49OE8]Woofy[/url], [url=http://goo.gl/bzBU1]Akita[/url], [url=http://goo.gl/SO5ug]VLC-GTK[/url], [url=https://tiny.cc/c2hnfz]Search[/url][/b]

User avatar
thunor
Posts: 350
Joined: Thu 14 Oct 2010, 15:24
Location: Minas Tirith, in the Pelennor Fields fighting the Easterlings
Contact:

Re: speeding up scripts

#25 Post by thunor »

sc0ttman wrote:1. Is it possible to execute a command defined in the main script, from within a GTK-Dialog button? If so, that would be great, but at the moment, anything like this in the GTKDialog GUI

Code: Select all

<button>
<action>my_function_name</action>
</button>
simply returns (in the terminal)

Code: Select all

my_function_name: command not found
Does <action>exec $SHELL -c 'my_function_name'</action> solve it? Somebody using Ubuntu+dash reported a similar problem and this was his fix.

Regards,
Thunor

User avatar
sc0ttman
Posts: 2812
Joined: Wed 16 Sep 2009, 05:44
Location: UK

Re: speeding up scripts

#26 Post by sc0ttman »

thunor wrote:
sc0ttman wrote:1. Is it possible to execute a command defined in the main script, from within a GTK-Dialog button? If so, that would be great, but at the moment, anything like this in the GTKDialog GUI

Code: Select all

<button>
<action>my_function_name</action>
</button>
simply returns (in the terminal)

Code: Select all

my_function_name: command not found
Does <action>exec $SHELL -c 'my_function_name'</action> solve it? Somebody using Ubuntu+dash reported a similar problem and this was his fix.

Regards,
Thunor
I'll have a look, thanks for the tip :)
[b][url=https://bit.ly/2KjtxoD]Pkg[/url], [url=https://bit.ly/2U6dzxV]mdsh[/url], [url=https://bit.ly/2G49OE8]Woofy[/url], [url=http://goo.gl/bzBU1]Akita[/url], [url=http://goo.gl/SO5ug]VLC-GTK[/url], [url=https://tiny.cc/c2hnfz]Search[/url][/b]

User avatar
frafa
Posts: 10
Joined: Thu 04 Aug 2011, 14:48
Location: MONTPELIER
Contact:

#27 Post by frafa »

Hello,
you can simplify in:

Code: Select all

<action>bash -c 'my_function_name'</action>
it's because of sub shell, in Ubuntu is dash
and dash does not support "export-f"

do the same for <input>
if <input> is a function

big_bass
Posts: 1740
Joined: Mon 13 Aug 2007, 12:21

#28 Post by big_bass »

speeding up scripts using arrays


when you have correctly formatted files there is another way to pull out values


*so if you start out creating a correctly formatted file
getting info is easy


here is an example using a .desktop
we all know that desktops are not formatted correctly or is there an official
line by line template that is used by all linux distros

but we could make a template :D

then read it with this
using shell and arrays
--------------------------------------------------------------------------------------------

Code: Select all


# advanced arrary use from info in advanced bash scripting modified by Joe Arose
# for using correctly formatted templates 

# this separates the strings using a pipe symbol this allows for spaces in strings to be read 
# to later be converted back to spaces 
# if not done this way every space is a new arrary value causing undesired word splitting 
# this fixes many problems with getting just one line of information

 
#this is beautiful it replaces the pipe for a space 
#echo ${desktop_array[4]//|/ }
 
#how that reads is echo array 4 and  //substitue all , pipe symbols, with a space
# it looks a bit like sed but using only the shell  


# set this to what you want
fileplace=/usr/share/applications/
filename=Axel-download-accelerator.desktop



desktop_array=( `cat "$fileplace$filename" | tr ' ' '|'`)


echo ${desktop_array[@]//|/ }

echo ${desktop_array[0]//|/ }

echo ${desktop_array[1]//|/ }

echo ${desktop_array[2]//|/ }

echo ${desktop_array[3]//|/ }

echo ${desktop_array[4]//|/ }

echo ${desktop_array[5]//|/ }

echo ${desktop_array[6]//|/ }

echo ${desktop_array[7]//|/ }

echo ${desktop_array[8]//|/ }

echo ${desktop_array[9]//|/ }

echo ${desktop_array[10]//|/ }


sample output

# echo ${desktop_array[0]//|/ }
[Desktop Entry]
#
# echo ${desktop_array[1]//|/ }
Encoding=UTF-8
#
# echo ${desktop_array[2]//|/ }
Name=Axel download accelerator
#
# echo ${desktop_array[3]//|/ }
Icon=mini-ftp.xpm
#
# echo ${desktop_array[4]//|/ }
Comment=Axel download accelerator
#
# echo ${desktop_array[5]//|/ }
Exec=puppydownload
#
# echo ${desktop_array[6]//|/ }
Terminal=false
#
# echo ${desktop_array[7]//|/ }
Type=Application
#
# echo ${desktop_array[8]//|/ }
Categories=X-Internet
#
# echo ${desktop_array[9]//|/ }
GenericName=Axel download accelerator
#

big_bass
Posts: 1740
Joined: Mon 13 Aug 2007, 12:21

#29 Post by big_bass »

I modified amigo's code to make desktops now write to and read from an array

*thanks for that snippet Gilbert it was really clever using the case for a pre filter grep and very fast

Code: Select all

> test.file
for DESKTOP_FILE in /usr/share/applications/* ; do
#for DESKTOP_FILE in /usr/share/applications/Editra.desktop ; do
    while read LINE ; do
      case $LINE in
         Name=*) NAME="${LINE[@]}"'|'   ;;
         Icon=*) ICON="${LINE[@]}"'|'   ;;
         #Terminal=*)
         #Type=*)
         Categories=*) CATS="${LINE[@]}"'|'   ;;
         Exec=*) EXEC="${LINE[@]}"'|'   ;;
         Comment=*) COMM="${LINE[@]}"'|'   ;;
      esac
   done < $DESKTOP_FILE
   echo $NAME$ICON$CATS$EXEC
   # To test the extract function below, use the following line instead of above
    echo '[Desktop_Entry]|'$NAME$ICON$CATS$EXEC$COMM | tr ' ' '_'>> test.file
done


desktop_array2=( `cat "$HOME/test.file"`)


# read line by line of the formatted array
# one problem was the Name= and the comment didnt get the spaces converted into
# the pipe symbol because the pipe was after the string with spaces
# but this gets fixed with underscores in the last echo using tr ' ' '_'


# how to read line by line from a  correctly  forrmatted  array now 
# just a sample of 5 diferent desktops read from the array desktop_array2

echo ${desktop_array2[0]//|/  } | tr ' ' '\n' | tr '_' ' '>testing0.txt
echo ${desktop_array2[1]//|/  } | tr ' ' '\n' | tr '_' ' '>testing1.txt
echo ${desktop_array2[2]//|/  } | tr ' ' '\n' | tr '_' ' '>testing2.txt
echo ${desktop_array2[3]//|/  } | tr ' ' '\n' | tr '_' ' '>testing3.txt
echo ${desktop_array2[4]//|/  } | tr ' ' '\n' | tr '_' ' '>testing4.txt




original code from amigo below

Code: Select all

> test.file
for DESKTOP_FILE in /usr/share/applications/* ; do
#for DESKTOP_FILE in /usr/share/applications/Editra.desktop ; do
   OUT=
   while read LINE ; do
      case $LINE in
         Name=*) NAME="${LINE#*=}"'|'  ;;
         Comment=*) OUT=$OUT"${LINE#*=}"'|'  ;;
         Icon=*) ICON="${LINE#*=}"'|'  ;;
         #Terminal=*)
         #Type=*)
         Categories=*) CATS="${LINE#*=}"'|'  ;;
         Exec=*) EXEC="${LINE#*=}"'|'  ;;
         #Comment=*) COMM="${LINE#*=}"  ;;
      esac
   done < $DESKTOP_FILE
   echo $NAME$ICON$CATS$EXEC
   # To test the extract function below, use the following line instead of above
   # echo $NAME$ICON$CATS$EXEC >> test.file
done 
Last edited by big_bass on Fri 19 Aug 2011, 23:39, edited 3 times in total.

User avatar
technosaurus
Posts: 4853
Joined: Mon 19 May 2008, 01:24
Location: Blue Springs, MO
Contact:

#30 Post by technosaurus »

If you use arrays, make sure to change the shabang to /bin/bash as they are bashisms.
Check out my [url=https://github.com/technosaurus]github repositories[/url]. I may eventually get around to updating my [url=http://bashismal.blogspot.com]blogspot[/url].

big_bass
Posts: 1740
Joined: Mon 13 Aug 2007, 12:21

#31 Post by big_bass »

I only use bash
* but if you are using another shell this runs only in bash*
you can take advantage of arrays using bash

(I credited amigo in a prior thread for the code base and pasted the original code a few posts ago )* I will include a diff patch for clarity

I put a safety in there all files get generated in /tmp/desktop
so if you are happy with the results you could manually copy over the
old desktops (thats your call) the user woud have to repackage all the packages with the new desktops to do the job right

I replaced the underscore with the "+" because some files may use underscore in names

Code: Select all

#!/bin/bash

make a template of all the desktops and lets you view them in /tmp/desktops 
so none of your original desktops get overwritten 

builds an array for speeding up any scripts that search info from the desktop

now all your desktops will have a format and an organized  template
the first line is [Desktop Entry],Name,Icon,Categories,Exec,Comment

and thats what you will expect to see when you search the desktops for info  


#[Desktop Entry]
#Name=AbiWord
#Icon=/usr/share/icons/abiword_48.png
#Categories=Application;Office;WordProcessor;GNOME;GTK;X-Red-Hat-Base;
#Exec=abiword
#Comment=Compose, edit, and view documents





# make a template  of the desktops regenerate all desktops  to the new simple template
# removes poorly formatted desktops and creates a standard  which allows later  for easy reading of strings 
# into an array to speed up scripts since the newly generated desktops maintain a standard format
# less commands are needed to filter data for output this is where all the time is wasted 
# having to parse poorly formatted files from the start if you have organized files
# everything is fast and easy to  parse the code

:>arraytest.txt
mkdir -p /tmp/desktops

for DESKTOP_FILE in /usr/share/applications/* ; do
#for DESKTOP_FILE in /usr/share/applications/Editra.desktop ; do
    while read LINE ; do
      case $LINE in
         Name=*) NAME="${LINE[@]}"'|'   ;;
         Icon=*) ICON="${LINE[@]}"'|'   ;;
         #Terminal=*)
         #Type=*)
         Categories=*) CATS="${LINE[@]}"'|'   ;;
         Exec=*) EXEC="${LINE[@]}"'|'   ;;
         Comment=*) COMM="${LINE[@]}"'|'   ;;
      esac      
   done < $DESKTOP_FILE
   echo $NAME$ICON$CATS$EXEC
   # To test the extract function below, use the following line instead of above
   # fixes spaces in the string names by replacing them with a "+" making a correctly formatted array
    echo '[Desktop+Entry]|'$NAME$ICON$CATS$EXEC$COMM | tr ' ' '+'  >>arraytest.txt
    #uncomment if you want to generate all new desktops in /temp/desktops
    echo '[Desktop+Entry]|'$NAME$ICON$CATS$EXEC$COMM | tr ' ' '+' | tr '| ' ' ' | tr ' ' '\n' | tr '+' ' '>/tmp/desktops/`basename $DESKTOP_FILE`
done
Attachments
amigo-orig.patch.gz
this is only to show the differences between amigos original work and my modifications
(737 Bytes) Downloaded 289 times

User avatar
technosaurus
Posts: 4853
Joined: Mon 19 May 2008, 01:24
Location: Blue Springs, MO
Contact:

#32 Post by technosaurus »

here is an example I cooked up that includes recursion, string manipulation, and integer math

Code: Select all

#!/bin/ash
A=$(($1/16))
HEX=0123456789ABCDEF
[ $A -gt 15 ] && dec2hex ${A} || printf ${HEX:$A:1}
printf ${HEX:$(($1%16)):1}
A=$(($1/16))
$1 is the input, this stores the "div" of the input by 16 (div is integer only without a remainder so 15 div 16 is 0 but 17 div 16 is 1)

HEX=0123456789ABCDEF
this shows how strings are really just an array of characters

[ $A -gt 15 ] && dec2hex ${A} || printf ${HEX:$A:1}
this is the recursive part, if the "div" is greater than 16, then we haven't gone enough hex place values, so call ourself with the div to shift back one ... note that nothing further happens until the last place value is reached (div is < 16) and the all recursive calls to dec2hex return... this last one only will print its div (in HEX format) the value after the first ":" is the starting point of the substring, and the value after the second ":" is the length of the substring

printf ${HEX:$(($1%16)):1}
similar to above printf statement except that it prints the "mod" (the remainder of input div 16) ... notice that all recursive calls will execute this code

now just to show the value of using functions instead of external scripts

try it like this:

Code: Select all

#!/bin/ash

dec2hex(){
A=$(($1/16))
HEX=0123456789ABCDEF
[ $A -gt 15 ] && dec2hex ${A} || printf ${HEX:$A:1}
printf ${HEX:$(($1%16)):1}
}

dec2hex $1
  • # time dec2hex 999999999999999999
    DE0B6B3A763FFFF
    real 0m0.034s
    user 0m0.032s
    sys 0m0.024s
    # time dec2hex 999999999999999999

    and if you want a generalized format for any base

    Code: Select all

    #!/bin/ash
    
    #note that base64 is traditionally A...Za...z0...9+/ (yeah wtf)
    dec2baseN(){
    A=$(($1/$2))
    STRING=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/
    [ $A -ge $2 ] && dec2baseN ${A} $2 || printf ${STRING:$A:1}
    printf ${STRING:$(($1%$2)):1}
    }
    
    dec2baseN $1 $2
Check out my [url=https://github.com/technosaurus]github repositories[/url]. I may eventually get around to updating my [url=http://bashismal.blogspot.com]blogspot[/url].

disciple
Posts: 6984
Joined: Sun 21 May 2006, 01:46
Location: Auckland, New Zealand

#33 Post by disciple »

Does anyone know: if you source another file, are functions from it run in a new subshell? I don't see why they would be... but I don't know.
Do you know a good gtkdialog program? Please post a link here

Classic Puppy quotes

ROOT FOREVER
GTK2 FOREVER

User avatar
technosaurus
Posts: 4853
Joined: Mon 19 May 2008, 01:24
Location: Blue Springs, MO
Contact:

#34 Post by technosaurus »

No, but it does take considerably longer, due to the extra file read.

Things that should be sourced include (not limited to...just examples
Localization (b/c you are only source 1 of X)
Configuration files (can be used/modified by other programs or the user)
A single file that contains all of your needed functions.

Things that usually shouldn't be sourced
Lots of files with a single or a few functions (each read adds time)
A self generated file (you can normally use a variable)
Check out my [url=https://github.com/technosaurus]github repositories[/url]. I may eventually get around to updating my [url=http://bashismal.blogspot.com]blogspot[/url].

disciple
Posts: 6984
Joined: Sun 21 May 2006, 01:46
Location: Auckland, New Zealand

#35 Post by disciple »

No
Ah, thanks, I confirmed that by testing, too :)

I don't know if anybody here would find it useful, but I see the Arch people maintain "A library providing UI functions for shell scripts"
https://github.com/Dieterbe/libui-sh#readme
Do you know a good gtkdialog program? Please post a link here

Classic Puppy quotes

ROOT FOREVER
GTK2 FOREVER

Post Reply