Useful scripts

This night I was compiling LibreOffice. By one o'clock it still wasn't finished.
I didn't want computer to stay up all night, so I wrote this little script:

Code:
#!/bin/sh
while [ "`uptime | awk 'BEGIN {FS=","} {print $5}' | sed 's/ //g'`" != '0.00' ]; do
  sleep 300
  echo wait
done
# wait 10 more minutes
sleep 600
shutdown -p now

It waits until load average for 15 minutes is 0.00, then waits another 10 minutes and shuts down PC.

You need to have your system configured to be able to shutdown pc, or run this script as root.

P.S.
It worked great and PC turned off at 3:27 :)
 
Why not just make install; shutdown?

In addition, your command can be simplified to:
`uptime | cut -d, -f5 | tr -d ' '`

Useless use of awk, sed, cat, and * should be punishable by repeated beatings.


For extra code golf points, here's the entire thing as short as I can make it on a single line:
f() { [ $(uptime | cut -d, -f5 = ' 0.00' ] && sleep 600 && halt -p || echo wait && sleep 300 && f;} f
 
Carpetsmoker said:
Why not just make install; shutdown?
I expected it will finish by 24:00 give or take.


In addition, your command can be simplified to:
`uptime | cut -d, -f5 | tr -d ' '`

Useless use of awk, sed, cat, and * should be punishable by repeated beatings.


For extra code golf points, here's the entire thing as short as I can make it on a single line:
f() { [ $(uptime | cut -d, -f5 = ' 0.00' ] && sleep 600 && halt -p || echo wait && sleep 300 && f;} f

I never used cut before, I'll take that into account in my next scripts.

Also I wrote this at about 1:00 o'clock (at night). It was a fast script to get things done.


Thanks for you input.
 
pkg_sanity

It does some basic sanity checks. It checks:
- for old FreeBSD binaries (ie. FreeBSD 8 binaries)
- for unresolvable shared libraries
- missing and/or leftover files in LOCALBASE

It doesn't:
- support pkgng (yet... I have no experience with pkgng)
- have a brain. Think before you act (see my signature).

I know there's already libchk, but that requires ruby, which I typically don't have installed.
There's also the `bsdadminscripts' port, but that's just confusing, it doesn't even install on my system, and if you need 464 lines of code to accomplish such a basic task, then IMHO you've put on the complicator's gloves. Also, I first wrote this a few years back before I learned of the bsdadminscripts.
 
Carpetsmoker said:
It doesn't:
- support pkgng (yet... I have no experience with pkgng)

The only reference to pkg_* tools I see in Your script ispkg_info -Wwhich is handled in PKGng bypkg which, the output is the same:

Code:
% pkg_info -W /usr/local/bin/lynx
/usr/local/bin/lynx was installed by package lynx-2.8.7.2,1

% pkg which /usr/local/bin/midori
/usr/local/bin/midori was installed by package midori-0.4.9_1

Also check this for 'mapping' between legacy pkg_* and PKGng tools:
https://wiki.freebsd.org/PkgPrimer
 
Thanks vermaden, I also do this to get all installed files:

Code:
grep -Ev '(^@|^\+)' | ${pkgdb}/*/+CONTENTS | sort -u > "${pkgfiles_tmpfile}"

Will pkg info -l \* work as expected?

Also, what's the proper way to detect pkgng usage?
 
" said:
version=$(uname -r | head -c 1)
This will stop working when 10.0-RELEASE is out ;)

I would use this one:
version=$(uname -r | cut -d '.' -f 1)

Carpetsmoker said:
Thanks vermaden, I also do this to get all installed files:

Code:
grep -Ev '(^@|^\+)' | ${pkgdb}/*/+CONTENTS | sort -u > "${pkgfiles_tmpfile}"

Will pkg info -l \* work as expected?

Try that:
% pkg info -l -a | grep '^/'

Carpetsmoker said:
Also, what's the proper way to detect pkgng usage?

Code:
% ls -l /var/db/pkg
total 100946
-r--r--r--  1 root  wheel    719028 2013.03.14 03:02 auditfile
-rw-r--r--  1 root  wheel  47235072 2013.03.13 20:18 local.sqlite
-rw-r--r--  1 root  wheel  55085056 2013.03.04 22:51 repo.sqlite

So I would check like that:
Code:
if [ -f /var/db/pkg/local.sqlite ]
then
  # PKGng case
  :
else
  # legacy pkg_* case
  :
fi

You may also check if it works to be sure:
Code:
% sqlite3 /var/db/pkg/local.sqlite '.tables'

... or compare the number of pkg_info lines count output with pkg info lines count output ;p
 
Carpetsmoker said:
Also, what's the proper way to detect pkgng usage?

That's a tough one because the system may have both sets of tools installed at the same time and with valid databases.

Maybe just make -V WITH_PKGNG and see if the answer is "yes".
 
Thanks, I've updated the script so that it should work with pkgng.

For the record, I now use this to detect pkgng usage:
Code:
[ -f ${pkgdb}/local.sqlite ] && [ "X$(make -V WITH_PKGNG)" != "X" ]
pkgng=$?

This way, people who set the variable in /etc/make.conf but haven't initialized it yet will still be fine, and people who just tried it out but then unset the variable in /etc/make.conf (but still have the sqlite db) will also be fine.

(Checking if WITH_PKGNG is `yes' is not correct, since /ports/Mk/* check for .if defined(WITH_PKGNG), so setting it to `y', `42', `migratory coconut', etc. in /etc/make.conf or using -DWITH_PKGNG is all valid).


version=$(uname -r | head -c 1)

This will stop working when 10.0-RELEASE is out

I would use this one:
version=$(uname -r | cut -d '.' -f 1)

Thank you for pointing out this rather silly mistake (*shame*).
 
kpa said:
Maybe just make -V WITH_PKGNG and see if the answer is "yes".

Currently we have WITH_PKGNG in /etc/make.conf but as PKGNG will be the default You would not put anything to /etc/make.confjust the same as now with legacy pkg_* tools.
 
Skelup.sh

I wrote a small script a bit ago to check users dot files and keep them in sync with the /usr/share/skel dir. Many of my users hose their user directories, so I have this run every night at 0330 to ensure that all users dot files are the same...

Feel free to edit and use. This is the first script I have ever written, so if you find anything that would make it easier/cleaner/better/safer, please don't be afraid to say something. I am always looking for constructive criticism. ;)

Code:
#!/usr/local/bin/bash

#######################################################################
#
# Written by: Me@mybox.net
# Purpose: Update usr dot files with updated skel dir
# Dependancies: None
# Revision Log: 1.0
#       3/17/13 - Started writting
#
#######################################################################

clear
DEBUG=0

SDIR="/usr/share/skel"
UDIR="/usr/home"
if [ "$DEBUG" -ge "1" ]; then
        printf "==> \$SDIR = %s" "$SDIR"
fi

usage ()
{
echo "Usage: skelup.sh [-d user directory] [-s skel dir]"
echo ""
echo "If no arguments are given user dir is set to: $UDIR"
echo "and skeleton dir is set to: $SDIR"
}

ERR=0
while getopts ":d:s:" OPT
do
case $OPT in
        :)
                echo "Option -$OPTARG requires an argument"
                ERR=1
                usage
                ;;
        \?)
                echo "Illegal options -$OPTARG"
                ERR=1
                usage
                ;;
        d)
                UDIR=$OPTARG
                ;;
        s)
                SDIR=$OPTARG
                ;;
esac
done

if [ $ERR -gt 0 ]; then
        echo "Options failed - exiting"
        exit 1
fi

if ! [ -z $UDIR ]; then
        echo "---> Checking for user dir sanity"
        sleep .5
        declare -a ETCU=($(cat /etc/passwd | grep -v '^#' | awk -F ":" '{print $1}'))
        FOUND=0
        for U in ${ETCU[@]}
        do
                if [ -e $UDIR/$U/.login ]; then
                        FOUND=$(( $FOUND + 1 ))
                fi
        done
        if [ $FOUND -ge 1 ]; then
                echo "Found $FOUND user directories out of ${#ETCU[@]} users in /etc/passwd"
                echo -n "$UDIR is a valid user dir - "; sleep .5; echo "PASSED"
                declare -a USERS=($(ls $UDIR))
        else
                echo "Didn't find ANY user directories in $UDIR - Exiting"
                exit 1
        fi
fi

echo "---> Checking for valid skeleton dir"
sleep .5
declare -a VS=($(ls $SDIR | grep '^dot.*'))

if ! [ -z ${VS[0]} ]; then
        echo -n "$SDIR is a valid skeleton dir - "; sleep .5; echo "PASSED"
        declare -a SFILES=(${VS[@]})
else
        echo "No valid dot files found in $SDIR - Exiting"
        exit 1
fi

echo "--------------------------------------------------------------------"
echo "---> Skeleton Dir:   $SDIR"
echo "---> User Dir:       $UDIR"
echo "--------------------------------------------------------------------"

sleep .5
echo "---> Checking for differences in User vs skel dir"

I=0
for U in ${USERS[@]}
do
        echo "------------- ${USERS[$I]} --------------"
        C=0
        for S in ${SFILES[@]}
        do
                STR=""
                STR="${SFILES[$C]}"
                FNAME="${STR:3}"
                DIF=$(diff -q $UDIR/${USERS[$I]}/$FNAME $SDIR/dot$FNAME)
                if ! [ -z "$DIF" ]; then
                        echo "$FNAME and dot$FNAME are DIFFERENT"
                        echo "---> Backing up user file as $FNAME-BAK"
                        cp $UDIR/${USERS[$I]}/$FNAME $UDIR/${USERS[$I]}/$FNAME-BAK
                        if [ -e $UDIR/${USERS[$I]}/$FNAME-BAK ]; then
                                echo "---> Backup successfull; Removing $FNAME"
                                rm $UDIR/${USERS[$I]}/$FNAME
                                cp $SDIR/dot$FNAME $UDIR/${USERS[$I]}/$FNAME
                                echo "---> Updating $FNAME with dot$FNAME"
                        else
                                echo "---> BACKUP DIDNT WORK - ABORTING"
                                break
                        fi
                fi
                C=$(( $C + 1 ))
        done
        I=$(( $I + 1 ))
        sleep .5
done

echo "======================================================================="
echo "|         ${#USERS[@]} users checked and updated with $SDIR            |"
echo "|     All users original files have been backed up as <file>-BAK      |"
echo "======================================================================="

exit 0
 
Small startup/re-attach script for sysutils/tmux. It sets up the SSH_AUTH_SOCK environment variable so that the ssh-agent(8) forwarding can be used in a re-attached session.

It's a bit of work in progress because I haven't yet been able to test if the clean-up using trap(1) is bullet-proof and what other signals I should catch.

Code:
#!/bin/sh

trap tmux-session-cleanup EXIT HUP

tmux-session-cleanup()
{
    if [ -L "${USERSOCKET}" ]; then
        echo "Removing ${USERSOCKET}"
        rm -f "${USERSOCKET}"
    fi
}

USERSOCKET="/tmp/.wrap_auth_sock-${USER}"

if [ -n "$TMUX" ]; then
    # Already in tmux session, do nada
    echo "Already in tmux session"
    exit 1
fi

# Set up ssh agent forwarding.

# Test if the symbolic link exists and is a link to a working socket.
if [ -L "${USERSOCKET}" ] && [ -e "${USERSOCKET}" ]; then
    echo "Refusing to overwrite existing link"
    exit 1
fi

if [ -n  "$SSH_TTY" ] && [ -n "${SSH_AUTH_SOCK}" ]; then
    ln -sf "$SSH_AUTH_SOCK" "${USERSOCKET}" # Create the symbolic link
    export SSH_AUTH_SOCK="$USERSOCKET" # Set SSH_AUTH_SOCK to the link
fi


TMUX_SESSION=$1

: ${TMUX_SESSION:="sshwrap"}

export STY="tmux-${TMUX_SESSION}"

tmux new-session -A -s "${TMUX_SESSION}"


I use this script as tmux-session.sh and I run it manually from a login shell.
 
This post is for educational purposes only, to better understand how streaming media servers work. For anyone who is interested.

Playing web page media streams in a media player without a browser. I approached it in several different ways.

Some websites with streaming media content hide the stream location, and the media will only play from within a browser with JavaScript enabled, so the scripts on the page will run. Looking through the pages source can reveal a playlist for the stream. However some servers stream their media in small segments that are time stamped. The playlist for the stream changes every few seconds and it contain the media location with time stamped info. Such as this playlist.m3u8:
Code:
#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-ALLOW-CACHE:YES
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:1744929
#EXTINF:10.000,
http://path/to/segment1744929_128.ts?sd=10&rebase=
#EXTINF:10.000,
http://path/to/segment1744930_128.ts?sd=10&rebase=
#EXTINF:10.000,
http://path/to/segment1744931_128.ts?sd=10&rebase=
In order to play the stream with a media player from the server, you have to download the playlist, replace the playlist every 10 seconds, keep the media player playing that same named playlist, and if the player runs out of stream it will exit. This particular stream is .aac audio. The media streams in 160k segments every 10 seconds. Then there is a small lag from segment to segment. If the stream is directed to a named pipe or -, the audio stream will be interrupted every 10 seconds while a new segment is downloaded.

My solution is to stream the media to file, append the segments to file, let the stream cache for a time, then playing that file with the media player. Getting the playlist every 5 seconds, then hash every time and rejecting anything that was already done gives an uninterrupted stream to the media player. Saving the stream to file also gives you a copy for later listening.

Code:
#!/usr/local/bin/bash

PROGN="m3u2aac"

URI="http://path/to/the/playlist.m3u8"

	fetchFile() 
	{ 
	_MYTMPFILE=`mktemp -p /tmp ${PROGN}.XXXXXXXXXX` && 
	{
	while [ true ]
	do 
	wget -O "${_MYTMPFILE}" "${URI}"

		HASH=($(md5sum "${_MYTMPFILE}"))
		[ "${#PREVHASH}" -eq 0 -o "${PREVHASH}" != "${HASH[0]}" ] &&

	{ 
	mplayer -playlist "${_MYTMPFILE}" -dumpstream -dumpfile "${_MYTMPFILE}.aac" &&
	cat "${_MYTMPFILE}.aac" >> ~/path/audio.aac
	} &

		PREVHASH="${HASH[0]}"
	sleep 5
	done
	} 
 
	rm -f "${_MYTMPFILE}" "${_MYTMPFILE}.aac"
	} 

fetchFile &
sleep 20 &&
mplayer ~/path/audio.aac

exit 0
Change URI= to your playlist, or have the script ask for it.
This was a scripting learning exercise for me.

This works also without dumping to file, but you'll get interuptions in play.
Code:
#!/usr/local/bin/bash

playlist=$(mktemp)
dumpfile=$(mktemp)
trap 'rm -f -- "$playlist" "$dumpfile"' 0

while :
do
wget -O "$playlist" http://path/to/the/playlist.m3u8 &&
mplayer -playlist "$playlist" -dumpstream -dumpfile "$dumpfile" &&
cat "$dumpfile"
sleep 10
done | 
mplayer -

This will simply dump the stream to file.
Code:
#!/usr/local/bin/bash

cd ~/test
a=1
while [ "$a" ];do
rm playlist.m3u8
wget http://path/to/the/playlist.m3u8
mplayer -playlist playlist.m3u8 -dumpstream -dumpfile $a &&
sleep 10
cat $a >> audio.aac &&
rm $a
let a=a+1
done
 
kpedersen said:
The following script disables the fan if the temp is lower than 45 and then enables it again at 55.

I know this isn't a brilliant idea but for some reason my Thinkpad x61 keeps its fan running trying to reach a very low temperature. It becomes quite cold for my wrist and quite uncomfortable for my lap ;)

This will only work when using the acpi_ibm module.

Code:
#!/bin/sh

disable_fan()
{
  echo "disable"
  sysctl dev.acpi_ibm.0.fan=0
}

enable_fan()
{
  echo "enable"
  sysctl dev.acpi_ibm.0.fan=1
}

try_disable_fan()
{
  if [ `sysctl -n dev.acpi_ibm.0.fan` = 1 ]; then
    disable_fan
  fi
}

try_enable_fan()
{
  if [ `sysctl -n dev.acpi_ibm.0.fan` = 0 ]; then
    enable_fan
  fi
}

if [ `id -u` != 0 ]; then
  echo "Error: Must be root"
  exit 1
fi

while [ true ]; do

  HIGHEST_TEMP=0
  TEMPERATURES=`sysctl -n dev.acpi_ibm.0.thermal`

  for TEMP in $TEMPERATURES; do
    if [ $TEMP -gt $HIGHEST_TEMP ]; then
      HIGHEST_TEMP=$TEMP
    fi
  done

  if [ $HIGHEST_TEMP -gt 55 ]; then
    try_enable_fan
  elif [ $HIGHEST_TEMP -lt 45 ]; then
    try_disable_fan
  fi

  sleep 5

done


Oh, that's nice. I wrote a similar script for Thinkpads. I'll post it later. :)
 
Now it's later ;)

Just a quick script I wrote for a friend whose Thinkpad fand was too noisy:

Code:
#!/bin/sh

# v0.2

# (C) 2013 Lars Engels <lars.engels@0x20.net>
#
#   BSD-style copyright and standard disclaimer applies.


sysctl="/sbin/sysctl"

check_interval=3

fan_max=7
fan_min=0


fan_level_mib="dev.acpi_ibm.0.fan_level"
#thermal_mib="dev.cpu.0.temperature"
thermal_mib="dev.acpi_ibm.0.thermal"
auto_control_mib="dev.acpi_ibm.0.fan"

level_1=40
level_2=45
level_3=50
level_4=55
level_5=60
level_6=65
level_7=70

print_verbose() {
	[ -n "${verbose}" ] && echo "$@"
}

enable_auto_control() {
	print_verbose "Enabling Fan auto control."
 	${sysctl} ${auto_control_mib}=1 2>/dev/null
}

disable_auto_control() {
	print_verbose "Disabling Fan auto control."
 	${sysctl} ${auto_control_mib}=0 2>/dev/null
}

get_fan() {
	${sysctl} -n ${fan_level_mib}
}

set_fan() {
	${sysctl} ${fan_level_mib}=${1} >/dev/null
}

exit_nomodule() {
	echo "No MIB ${auto_control_mib} found! Is acpi_ibm.ko not loaded?"
	exit 1
}

print_status() {
	${sysctl} -n ${thermal_mib} 2>/dev/null |
 	while read cpu_temp mpci_temp hdd_tmp gpu_tmp ibatt_temp ubatt_temp crap; do
        	echo "CPU:              ${cpu_temp}"
        	echo "Mini PCI Module:  ${mpci_temp}"
        	echo "HDD:              ${hdd_tmp}"
        	echo "GPU:              ${gpu_tmp}"
        	echo "Built-in battery: ${ibatt_temp}"
        	echo "UltraBay battery: ${ubatt_temp}"
		echo "Fan Level:        $(get_fan) of ${fan_max}"
	done
}

trap print_status INFO
trap enable_auto_control INT


[ "${1}" = "-v" ] && verbose=1

disable_auto_control || exit_nomodule

while sleep ${check_interval}; do
	cur_temp=$(${sysctl} -n ${thermal_mib} | cut -d" " -f1)

	if   [ ${cur_temp} -lt ${level_1} ]; then
		level=${fan_min}
	elif [ ${cur_temp} -lt ${level_2} ]; then
		level=1
	elif [ ${cur_temp} -lt ${level_3} ]; then
		level=2
	elif [ ${cur_temp} -lt ${level_4} ]; then
		level=3
	elif [ ${cur_temp} -lt ${level_5} ]; then
		level=4
	elif [ ${cur_temp} -lt ${level_6} ]; then
		level=5
	elif [ ${cur_temp} -lt ${level_7} ]; then
		level=6
	else
		level=7
	fi

	set_fan ${level}
	print_verbose "Temperature=${cur_temp};Fan-Level=${level}"
done
 
If anyone can use this. A couple of scripts that I wrote for Google text to speech, and Google text to text translation. They work from shell and allow you to translate until you quit.

The text to speech script concatenates to $FILE.mp3 so you can make a single file out of 100 char max. segments. The text to text dumps the output to sdout, redirect to $FIlE if you want. You might want to take it easy on how many times a minute you hit their server.

Text to text
Code:
#! /usr/local/bin/bash

# Translate text using google. No google account needed.
# Requires curl, awk, iconv, html2text
# Language are:
# af ar az be bn bg bs ca cub zh-CN zh-TW cs cy da de en en_us en_gb en_au 
# el es et eu fa fi fr ga gl gu ht hi hmn hr hu hy is id it iw ja jw ka km 
# kn ko la lv lt mk mr ms mt no nl pl pt ro ru sr sk sl sq sw sv ta te th tl 
# tr uk ur vi yi

clear
OPTIONS="Input_Lang Output_Lang Enter_Text Translate Quit"
echo "Press Enter at any time to return to menu."
echo "Select an option:"
select opt in $OPTIONS; do

if [ "$opt" = "Quit" ]; then
clear
exit

elif [ "$opt" = "Input_Lang" ]; then
echo "Language options are:"
echo "en de fr es it" # Add languages here.
echo "What input language"
read ILAN

elif [ "$opt" = "Output_Lang" ]; then
echo "Language options are:"
echo "en de fr es it" # Add languages here.
echo "What ouput language"
read OLAN

elif [ "$opt" = "Enter_Text" ]; then
echo "Enter text"
read TEXT

elif [ "$opt" = "Translate" ]; then

result=$(curl -s -i --user-agent "" -d "sl=$ILAN" -d "tl=$OLAN" --data-urlencode "text=$TEXT" http://translate.google.com)
encoding=$(awk '/Content-Type: .* charset=/ {sub(/^.*charset=["'\'']?/,""); sub(/[ "'\''].*$/,""); print}' <<<"$result")

iconv -f $encoding <<<"$result" |  awk 'BEGIN {RS="</div>"};/<span[^>]* id=["'\'']?result_box["'\'']?/' | html2text

else
echo "Bad option"
fi; done

Text to voice
Code:
#! /usr/local/bin/bash

# Text to speech conversion using google text to voice. No google account needed.
# Requires wget
# 100 char. max. Output to "$NAME.mp3"
# Language are:
# af ar az be bn bg bs ca cub zh-CN zh-TW cs cy da de en en_us en_gb en_au 
# el es et eu fa fi fr ga gl gu ht hi hmn hr hu hy is id it iw ja jw ka km 
# kn ko la lv lt mk mr ms mt no nl pl pt ro ru sr sk sl sq sw sv ta te th tl 
# tr uk ur vi yi

clear
OPTIONS="Language Enter_Text Filename Translate Quit"
echo "Press Enter at any time to return to menu."
echo "Select an option:"
select opt in $OPTIONS; do

if [ "$opt" = "Quit" ]; then
clear
exit

elif [ "$opt" = "Language" ]; then
echo "Language options are:"
echo "en de fr es it" # Add languages here.
echo "What Language?"
read LNG

elif [ "$opt" = "Enter_Text" ]; then
echo "Enter text to translate to voice"
read WORDS

elif [ "$opt" = "Filename" ]; then
echo "Output file name?"
read NAME

elif [ "$opt" = "Translate" ]; then
URL="http://translate.google.com/translate_tts?tl=${LNG}&q="
wget -q -U Mozilla -O - "$URL""$WORDS" >> "$NAME".mp3

else
echo "Bad option"
fi; done
 
cutleaves-ng

I wrote a cutleaves script for PKGNG. It deletes packages, that are not needed as a dependency for other packages. Instead of asking you for every package, if you want to delete it (y|n) it gives you a list to edit. If not run as root, it uses sudo where needed.

Code:
#! /bin/sh

# cutleaves-ng

# pkg version option: -I index, -P ports, -R reposity catalogue
PVO="-I"
# change this if you wrote your own meta port
METAPORT="ports-mgmt/wanted-ports"

usage () {
     cat << EOF
Usage: $(basename $0) [option]

Delete interactively out-of-date-packages that are not required as a
dependency by other packages.

Options:
     -h       show this message
     -a       include up-to-date-packages
     -l FILE  log output to file

EOF
exit
}

ALL=
LOGFILE=/dev/null
while getopts 'ahl:' OPTION; do
     case $OPTION in
	  a)	ALL=YES;;
	  h)	usage;;
	  l)	LOGFILE=$OPTARG;;
	  *)	usage;;
     esac
done

if [ $(whoami) = root ]; then
     SUDO=
elif which sudo >/dev/null; then
     SUDO=sudo
else
     echo "Sorry." >&2
     exit 77
fi

echo "# List of packages to be deleted" >/tmp/$$leaves
echo "# To keep a package remove the line." >>/tmp/$$leaves
echo "# Type [F2] to register a package with wanted-ports(1)." >>/tmp/$$leaves
echo "# Type [F3] to see pkg info -f." >>/tmp/$$leaves

if [ "$ALL" == "YES" ]; then
     pkg query -e "%#r == 0 && %o != $METAPORT" %o >>/tmp/$$leaves
else
     pkg version $PVO -oL = | awk '{print $1}' >/tmp/$$update
     pkg query -e "%#r == 0 && %o != $METAPORT" %o | \
	  grep -xf /tmp/$$update >>/tmp/$$leaves 
fi

# don't want to run vim as root
if [ $SUDO ] && which vim >/dev/null; then
     vim "+map <F2> :! $SUDO wanted-ports -a <cWORD> <CR>" \
	  '+map <F3> :! pkg info -f <cWORD> \| more <CR>' /tmp/$$leaves
else
     ${EDITOR:-vi} /tmp/$$leaves
fi

# make sure user is sudoer before getting into trouble
if $SUDO true; then
     echo "$(basename $0) $(date)" >"$LOGFILE"
     echo >>"$LOGFILE"
     grep -v "^#" /tmp/$$leaves | xargs -n 1 $SUDO pkg delete -y | \
     	  tee -a "$LOGFILE"
     rm /tmp/$$leaves
else
     echo "Aborting. List is saved here: /tmp/$$leaves." >&2
fi
[ -f /tmp/$$update ] && rm /tmp/$$update 
exit 0
 
Google Text to Text Translation

@teckk,

I have a problem with the iconv(1) conversion, despite it supporting the encoding charset ISO-8859-1 it throws the following error:
Code:
unsupportedrsion from ISO-8859-1
iconv: try 'iconv -l' to get the list of supported encodings

iconv(1) on BSD has:
Code:
[CMD]% iconv -l | grep ISO-8859-1[/CMD]
CP819 IBM819 ISO-8859-1 ISO-IR-100 ISO8859-1 ISO_8859-1 ISO_8859-1:1987 L1 LATIN1 CSISOLATIN1
ISO-8859-10 ISO-IR-157 ISO8859-10 ISO_8859-10 ISO_8859-10:1992 L6 LATIN6 CSISOLATIN6
ISO-8859-11 ISO8859-11 ISO_8859-11
ISO-8859-13 ISO-IR-179 ISO8859-13 ISO_8859-13 L7 LATIN7
ISO-8859-14 ISO-CELTIC ISO-IR-199 ISO8859-14 ISO_8859-14 ISO_8859-14:1998 L8 LATIN8
ISO-8859-15 ISO-IR-203 ISO8859-15 ISO_8859-15 ISO_8859-15:1998 LATIN-9
ISO-8859-16 ISO-IR-226 ISO8859-16 ISO_8859-16 ISO_8859-16:2001 L10 LATIN10

This is the full log of bash -x google-translate.sh

Any clue about what happens?

PS. I'm using the Citrus iconv encoding. See BSD-licensed libiconv in base system for more details.
 
Last edited by a moderator:
vermaden said:
Currently we have WITH_PKGNG in /etc/make.conf but as PKGNG will be the default You would not put anything to /etc/make.confjust the same as now with legacy pkg_* tools.

Apparently ports-mgmt/portmaster has been doing this for a while now to test if PKGNG is used:

pkg info pkg >/dev/null 2>&1 && use_pkgng=yes

This will return error code !=0 properly and silently if there's only the interactive bootstrap /usr/sbin/pkg available.
 
@cpu82

I don't know. Your locale is ISO 8859-1? Does it work if you start a terminal with UTF-8? Example:
Code:
xterm -en utf-8 -e bash -x bash -x google-translate.sh
Or in .bashrc, example:
Code:
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
To make these changes active in the current shell: source ~/.bashrc.

Also I just checked, that script works ok for me in
Code:
#! /bin/sh
You may not like the translation that Google gives, as one member pointed out, but it works.
 
Last edited by a moderator:
teckk said:
I don't know. Your locale is ISO 8859-1? Does it work if you start a terminal with UTF-8? Example:
Code:
xterm -en utf-8 -e bash -x bash -x google-translate.sh

Thanks for your reply, but this doesn't work either.

My .cshrc locale variables:
Code:
setenv	LANG es_ES.UTF-8
setenv	LC_ALL es_ES.UTF-8

Note that I changed the shell to bash(1)(), but it still occurs the same error.

I think I missed something, so I need digging more :e

PS. In the meantime, I use this one that only needs curl(1)() and sed(1)():
Code:
#!/usr/local/bin/bash

USAGE="Usage: 
       $0 en es Lovely spam!
Some codes: en|fr|de|ru|nl|it|es|ja|la|pl|bo
All language codes:
http://code.google.com/apis/ajaxlanguage/documentation/reference.html#LangNameArray"

if [ "$#" == "0" ]; then
    echo "$USAGE"
    exit 1
fi

FROM_LNG=$1
TO_LNG=$2

shift 2
QUERY=$*

UA="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.2) Gecko/20040803"
URL="http://translate.google.com/translate_a/t?client=t&hl=en&sl=$FROM_LNG&tl=$TO_LNG&otf=2&multires=1&ssel=0&tsel=0&sc=1"
curl  --data-urlencode "text=$QUERY" -A $UA -s -g -4 $URL | sed 's/","/\n/g' | sed 's/\]\|\[\|"//g' | sed 's/","/\n/g' | sed 's/,[0-9]*/ /g'

PPS. I tested the script in other PC and it fails at the same point :\
 
cpu82 said:
Thanks for your reply, but this doesn't work either.

My .cshrc locale variables:
Code:
setenv	LANG es_ES.UTF-8
setenv	LC_ALL es_ES.UTF-8

Note that I changed the shell to bash(1)(), but it still occurs the same error.

I think I missed something, so I need digging more :e

Also set your locale in your ~/.xinitrc / ~/.xsession. Check how I do it: https://github.com/graudeejs/dot.files/blob/master/dot.xinitrc#L2
https://github.com/graudeejs/dot.files/blob/master/dot.profile
https://github.com/graudeejs/dot.files/blob/master/dot.shrc
 
Back
Top