Bash script to select fast mirror

I've written this basic script which can be used to select a mirror from pacman's mirrorlist file which minimizes the response time between you and the mirror. This often leads to satisfactory download speeds. You might have to change some of the variables at the beginning of the script to suit your needs.
#!/bin/bash
# mirrorize v0.1 - Fast mirror selector for pacman
# Copyright (C) 2009 sin
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
if [ ! "$UID" == "0" ]; then
echo "[+] you cannot perform this operation unless you are root." 1>&2
exit
fi
MIRROR_PATH="/etc/pacman.d/mirrorlist.pacorig"
BEST_MIRROR=""
BEST_TIME=300 # ms
TMP=$(mktemp)
function cleanup() {
rm -f $TMP
trap cleanup SIGINT SIGTERM
cp $MIRROR_PATH $MIRROR_PATH.backup
for mirror in `cat $MIRROR_PATH | sed 's/#//g' | grep ':' | sed 's/Server = //g' | sed 's/ftp:\/\///g' | sed 's/http:\/\///g' | sed 's/\/.*//g'`; do
M=$(ping $mirror -B -w 2 -n -c 4 2>/dev/null | grep rtt | awk -F '/' '{print $5}')
if [ ! -z "$M" ]; then
M=${M/.*};
if [ "$M" -lt "$BEST_TIME" ]; then
BEST_TIME=$M
BEST_MIRROR=$mirror
echo "[+] found a faster mirror [$BEST_MIRROR] => response time = $BEST_TIME ms"
fi
fi
done
if [ ! -z "$BEST_MIRROR" -a ! "$BEST_MIRROR" = "ftp.archlinux.org" -a ! -z "$BEST_TIME" ]; then
sed 's/^Server/#Server/g' $MIRROR_PATH > $TMP; cat $TMP > $MIRROR_PATH
cat $TMP > $MIRROR_PATH
line=$(egrep -in $BEST_MIRROR $MIRROR_PATH | uniq | sed 's/:.*//g' | head -1)
extension="ftp"
cat $MIRROR_PATH | head -$line | tail -1 | egrep -i "ftp:" 1>/dev/null
[ $? -eq 0 ] || extension="http"
sed -e "${line}s/^#Server = .*${BEST_MIRROR}/Server = ${extension}:\/\/${BEST_MIRROR}/g" $MIRROR_PATH > $TMP
cat $TMP > $MIRROR_PATH
fi
cleanup
pacman -Syy
Last edited by dimigon (2009-03-07 23:36:46)

Heema wrote:
made a little update for it so it doesnt requir root acount
it also now adds last sync times to the results
#!/bin/bash
# mirrorize v0.1 - Fast mirror selector for pacman
# Copyright (C) 2009 sin
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
MIRRORLIST=$(mktemp)
cat /etc/pacman.d/mirrorlist > $MIRRORLIST
MIRROR_PATH="$MIRRORLIST"
BEST_MIRROR=""
BEST_TIME=300
TMP=$(mktemp)
LIST=$(mktemp)
wget -q "http://users.archlinux.de/~gerbra/mirrorcheck.html" -O /tmp/mirrorcheck.html
function cleanup() {
rm -f $TMP
rm -f $LIST
rm /tmp/mirrorcheck.html
trap cleanup SIGINT SIGTERM
echo "Pinging Servers..."
for mirror in `cat $MIRROR_PATH | sed 's/#//g' | grep ':' | sed 's/Server = //g' | sed 's/ftp:\/\///g' | sed 's/http:\/\///g' | sed 's/\/.*//g'`; do
M=$(ping $mirror -B -w 2 -n -c 4 2>/dev/null | grep rtt | awk -F '/' '{print $5}')
if [ ! -z "$M" ]; then
M=${M/.*};
if [ "$M" -lt "$BEST_TIME" ]; then
BEST_MIRROR=$mirror
LASTSYNC=$(cat /tmp/mirrorcheck.html | grep -A 13 "$BEST_MIRROR" | tail -n 1 | sed 's/<td>//g' | sed 's/()<\/td>//g' | cut -c 7-)
echo "$M $mirror Not synced since: $LASTSYNC" >> $LIST
fi
fi
done
cat $LIST | sort -n
cleanup
Cheers! Nice one

Similar Messages

  • My first bash script - update mirrors and then update your system.

    Like the title says, this is my first attempt at a bash script.
    I wrote it to make it a tiny bit easier for my wife to keep her system up to date without needing to remember the terminal commands.  She runs it via an entry in her openbox menu.
    It calls on reflector to check all available mirrors for the most up to date and then use rankmirrors to find the fastest 5 and write them to /etc/pacmand.d/mirrorlist
    Finally, it syncs and upgrades via the command pacman -Syyu
    #!/bin/bash
    # runs reflector to optimize mirrors
    echo "I'm afraid I can't do that Dave"
    sudo reflector -l 5 -r -o /etc/pacman.d/mirrorlist
    echo " I hope you trust me..."
    echo " "
    sleep 2s
    # updates system
    sudo pacman -Syyu

    I've scavenged some code to take care of the root thing, but why rebase vs pacman?  After reading up on rebase a bit, I'm not quite sure how to use it to complete the upgrade once it's updated everything.

  • [Solved] Selecting folder span in bash script

    Hey all,
    Recently, I decided to get an audio-book from Audible and discovered the mp3 player they advertise about is only for ipods.  This meant that the only legit way to transfer it to my mp3 player (an .aa file/DRM protected) was to use iTunes burn it to multiple cds.  Doingthis had the book span 14 disks and now I'm trying to put it back together.  I used a great program called 'ripit' to rip the files back to Linux and now I'm faced with the task of concatenating the files back together again.  Ripit ripped the disks to 14 separate folders:
    Unknown Artist - Unknown Album
    Unknown Artist - Unknown Album 1
    Unknown Artist - Unknown Album 2
    Unknown Artist - Unknown Album 13
    To get these to appear in correct order I first rename the first album:
    mv Unknown\ Artist\ -\ Unknown\ Album/ Unknown\ Artist\ -\ Unknown\ Album\ 0
    replaced white spaces with hyphens (necessary for the next step):
    find -name "* *" -type d | rename 's/ /-/g'
    Zeropad the numbers to show in the right order (using this persons excellent script - http://www.walkingrandomly.com/?p=2850):
    for i in *; do mv "$i" $(zeropad "$i"); done
    #!/bin/bash
    # zeropad
    # Filter that will take input with basic numbering and zero pad it (i.e. file002)
    # e.g. mv file1.png `$(zeropad) $i`
    # http://www.walkingrandomly.com/?p=2850
    num=`expr match "$1" '[^0-9]*\([0-9]\+\).*'`
    paddednum=`printf "%03d" $num`
    echo ${1/$num/$paddednum}
    So now my directories look like this:
    Unknown-Artist---Unknown-Album-000
    Unknown-Artist---Unknown-Album-001
    Unknown-Artist---Unknown-Album-013
    Now I'm trying to create a bash script that will put this mp3s back together again.  mp3cat is the right utility to do this so I need to create a bash script that I can tell what folders to use to put them together.  Originally the book from Audible came in three parts:
    SK...part1.aa
    SK...part2.aa
    SK...part3.aa
    part 1 covers directories 000 to 004, part 2 005 to 008, part 3 009 to 013.  The script though I'd like to be generic (to be able to accept input if I decided to ever do this again).  Here it is thus as I have it so far figured out:
    echo "Join multiple mp3s from which folders?"
    echo -n "First folder number [0xx]: "
    read first_folder
    echo -n " to folder number [0xx]: "
    read final_folder
    echo -n " Name of file [name].mp3: "
    read filename
    for f in Unknown-Artist---Unknown-Album-[$first_folder-$final_folder]; do
    cat "$f"/*.mp3 | mp3cat - - > "$filename".mp3
    done
    I'd like to be able to input which directory to begin with and then input which directory to end with.  My use of [$first_folder-$final_folder] here shows my limited use of bash and I know that this this is only going to work for a single digit.  Any ideas what I can do here?
    Last edited by Gen2ly (2011-09-19 02:25:04)

    If there are spaces in the filenames then using globbing won't change anything. When stored in an array the new elements are split at spaces. This has the same problem as using ls. edit: ok so, "newer" versions of bash won't split the elements at spaces but the spaces still screw up when the array is expanded to command arguments.
    As usual all problems of existence are just a primitive form of bending. I mean, sorting! Crap. No need to remove the spaces and rename everything. sort and awk like spaces.
    # Must... have... number!
    mv "Unknown Artist - Unknown Album" "Unknown Artist - Unknown Album 0" \
    2>/dev/null
    # Sort & awk read as many number chars as possible, then give up.
    # ./Unknown Artist - Unknown Album 1/Track 1.mp3
    # (Fields) 6_/*^^^^^^ *^^^^\_7
    find . -name '*.mp3' | sort -n -k6 -k7 | \
    # $6+0 coerces $6 into a number.
    awk -v beg="$1" -v end="$2" '$6+0 >= beg && $6+0 <= end' |
    # Use NULL chars instead of newlines to make xargs happy.
    tr '\n' '\0' | xargs -0 cat
    # Without NULL chars and -0, xargs splits on lines AND spaces. Bad.
    Instead of changing the data (paths) to make it sort lexicographically, I simply sorted the data explicitly. Two args: beginning number and ending number. It's probably too late, since you renamed everything but maybe you can use the tr | xargs trick. Avoid using bash arrays or get rid of the spaces in the filenames.
    Last edited by juster (2011-09-18 13:02:59)

  • What do you think of my Bash Script? What about the error checking?

    Well what do you think of this Bash script
    It works
    I gave it some problems (i.e. unpluged the ethernet, messed up the URL's, uninstaled some programs...) to see if would report errors and stop or just keep going... But it did
    I just kind of thought up a way to do some error checking with the commands that I know.....
    What is a better way to do error checking?
    What do you think I should add/Do to this script?
    #!/bin/bash
    # Shell script to make a USB Tumb Drive for Flashing BIOS on a Lenovo Ideapad Y510.
    # This script needs to be owned and run as ROOT with the "sudo command"
    # i.e. sudo usbbiosflasher
    # If you have anyideas send me a PM on ubuntufourms.org my user name is HunterThomson
    # Name/Rename this script usbbiosflasher and save it to the ~/home directory.
    # Then run the command- chown root:root usbbiosflasher
    # Then run the command- chmod 755 usbbiosflasher
    # Then copy the script to the directory /usr/bin.
    # Run this comand to do that- sudo cp ~/usbbiosflasher /usr/bin
    # You also must have the program "mbr" installed
    # You can install the mbr program by running this comand in the shell on Ubuntu
    # sudo apt-get install mbr
    # In Arch Linux you have to get it from Aur
    # First you will need to know a few things...
    # You will also need to know the Mount Point i.e. /media/disk and the /dev path i.e. /dev/sdb1.
    # You can find these by using the df -T comand.
    # Run df -T in the shell. Then plug in the USB Thumb Drive and run the df -T comand agin.
    # The new listing is the USB Thumb Dirve.
    # Also check to make sure the File System tipe is vFAT or FAT16 or FAT32.
    # If it is not use gparted to format it to FAT32.
    # I am farly certen that all USB Thumb drives come formated with FAT file system out of the BOX.
    # You may want to fromat it anyway just to make sure.
    echo "Interactive Shell Script to Make a USB Thumb Drive \for Flashing BIOS On a Lenovo Ideapad Y510"
    echo ""
    echo "You will need to have the program mbr installed"
    echo "If you are on Ubuntu Linux you can retreve it form the repositories"
    echo "If you are on Arch Linux you will need to get it from the Aur repository"
    echo "Open anuther shell and \do that now..."
    echo ""
    verify="n"
    while [ "$verify" != y ]
    do
    printf "Do you have mbr installed... yes or no?"
    read AN1
    echo ""
    printf "You answered... $AN1 I have installed mbr. Is this correct... y or n?"
    read verify
    done
    echo ""
    if [ "$AN1" == "no" ]
    then
    echo "Install mbr now. Then run this script agin"
    exit
    else
    echo "contunuing script"
    fi
    echo ""
    # The next comand will make a directory to put needed files into. Note this file and everything init will be owned by root.
    mkdir ~/usbbiosfiles && check1="yes"
    if [ "$check1" = "yes" ]
    then
    echo "Made directory usbbiosfiles... OK"
    else
    echo "Could not \make directory usbbiosfiles"
    echo "look above \for \info"
    echo "Fix the problem and run this scrip agin"
    exit
    fi
    # The next two comands will get the FreeDOS file and the .ROM file.
    cd ~/usbbiosfiles && checka="yes"
    if [ "$checka" = "yes" ]
    then
    echo "Changing to the usbbiosfiles directory... OK"
    else
    echo "Could not Change to the usbbiosfiles directory"
    echo "look above \for \info"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    wget "http://www.fdos.org/bootdisks/autogen/FDOEM.144.gz" && check2="yes"
    if [ "$check2" = "yes" ]
    then
    echo "Download of FreeDOS... OK"
    else
    echo "Could not Download FreeDOS"
    echo "look above \for \info"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    wget "http://ubuntuforums.org/attachment.php?attachmentid=78460&d=1216648756" && check3="yes"
    if [ "$check3" = "yes" ]
    then
    echo "Download of the BIOS.ROM \file... OK"
    else
    echo "Could not Downlad the BIOS.ROM \file"
    echo "look above \for \info"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    # The next comand will name the .ROM file to the right name.
    mv ~/usbbiosfiles/attachment.php?attachmentid=78460\&d=1216648756 ~/usbbiosfiles/06CN29WW.bios.update.tar.bz2 && check4="yes"
    if [ "$check4" = "yes" ]
    then
    echo "Renameing of the BIOS.ROM \file... OK"
    else
    echo "Could not rename the BIOS.ROM \file"
    echo "look above \for \info"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    echo ""
    # The next two comands set the variables. DEVX for the path i.e. /dev/xxx and MOUNTX for the mount point i.e. /media/xxx
    verify="n"
    while [ "$verify" != y ]
    do
    echo "You will need to know the Mount Point and the dev Path. You will also need to \make sure the File System \type is vFAT, FAT16 or FAT32."
    echo ""
    echo "With the USB Thumb Drive unpluged, Open another shell and run the comand df -T Then plug \in the USB Thumb Drive and run the comand df -T one \more time. The new device listed is the USB Thumb Drive. Note the Mount Point and The dev Path and the File system Type i.e. vFAT... If the File System \type is not vFAT, FAT16 or FAT32 you will need to fromat it with gparted. You may want to format the USB Thumb Drive anyway just to \make sure. In any \case delete all files and directorys on the USB drive before you go any ferther with this program."
    echo ""
    printf "Enter the dev path the USB Thumb Drive is at?"
    read DEVX
    echo ""
    echo "Are you sure $DEVX is the dev path of the USB Thumb Drive... y or n?"
    read verify
    done
    echo ""
    verify="n"
    while [ "$verify" != y ]
    do
    printf "What is the Mount Point of the USB Thumb Drive?"
    read MOUNTX
    echo ""
    echo "Are you sure $MOUNTX is the Mount Point of the USB Drive... y or n?"
    read verify
    done
    echo ""
    install-mbr --enable A1 --partition 1 --force --timeout 0 $DEVX && check5="yes"
    if [ "$check5" = "yes" ]
    then
    echo "Installing MBR on USB Thumb Dirve... OK"
    else
    echo "Could not install MBR on USB Thumb Drive"
    echo "look above \for \info"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    tar xjf ~/usbbiosfiles/*.tar.bz2 && check7="yes"
    if [ "$check7" = "yes" ]
    then
    echo "Unpacking BIOS.ROM file... OK"
    else
    echo "Could not unpack BIOS.ROM file"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    gunzip ~/usbbiosfiles/FDOEM.144.gz && check8="yes"
    if [ "$check8" = "yes" ]
    then
    echo "Unpacking FreeDOS files... OK"
    else
    echo "Could not unpack FreeDOS files"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    mkdir ~/usbbiosfiles/fdoem144 && check9="yes"
    if [ "$check9" = "yes" ]
    then
    echo "Made directory fdoem144 in direcoty usbbiosfiles... OK"
    echo ""
    echo "Going to \sleep \for 5secs"
    else
    echo "Could not make directory fdoem144 in usbbiosfiles directory"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    modprobe loop && sleep 5 && check0="yes"
    if [ "$check0" = "yes" ]
    then
    echo "Modprobeing loop... OK"
    else
    echo "Could not \modprobe loop"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    mount -o loop ~/usbbiosfiles/FDOEM.144 ~/usbbiosfiles/fdoem144 && check10="yes"
    if [ "$check10" = "yes" ]
    then
    echo "Mounting FreeDOS on the fdoem144 directory... OK"
    else
    echo "Could not \mount FreeDOS on the fdoem144 directory"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    cp ~/usbbiosfiles/fdoem144/* $MOUNTX && check11="yes"
    if [ "$check11" = "yes" ]
    then
    echo "Copying FreeDOS files to $MOUNTX... OK"
    else
    echo "Could not copy FreeDOS files to $MOUNTX"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    cp ~/usbbiosfiles/*.ROM $MOUNTX && check12="yes"
    if [ "$check12" = "yes" ]
    then
    echo "Copying BIOS.ROM files to $MOUNTX... OK"
    else
    echo "Could not copy BIOS.ROM files to $MOUNTX"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    sync && check13="yes"
    if [ "$check13" = "yes" ]
    then
    echo "Runing the syncing command... OK"
    else
    echo "Could not run the syncing command"
    echo "look above \for \info"
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this scrip agin"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    rm -r ~/usbbiosfiles
    exit
    fi
    umount ~/usbbiosfiles/fdoem144 && check14="yes"
    if [ "$check14" = "yes" ]
    then
    echo "Unmounting of FreeDOS... OK"
    else
    echo "Could not unmount FreeDOS"
    echo "Look above for errors or problems reported and fix the problem"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this script agin"
    rm -r ~/usbbiosfiles
    exit
    fi
    verify="n"
    while [ "$verify" != y ]
    do
    printf "Do you see any errors... yes or no?"
    read AN2
    echo ""
    printf "You answered... $AN2 to errors. Is this correct... y or n?"
    read verify
    done
    echo ""
    if [ "$AN2" == "yes" ]
    then
    echo "User Repoted... Error"
    echo "Look above for errors or problems reported and fix the problem"
    echo ""
    echo "removeing directory usbbiosfiles..."
    echo ""
    echo "Reformat the USB Stick to FAT32 with gparted"
    echo "Fix the problem and run this script agin"
    rm -r ~/usbbiosfiles
    exit
    else
    echo "Success"
    echo "I did a lot of error checking too and didnt find anything"
    echo ""
    echo "Go get a pen and paper to write down these instructions"
    printf "Then hit the Enter to continue"
    read WAIT
    echo ""
    echo "Now leave the USB Thumb Drive pluged into your computer and Reboot. When the Lenovo Logo POST screen appears hit F2 to enter the CMOS setup utility. Go over to BOOT tab and go down to HardDrive \(Not Boot Order) \then \select the USB Thumb Drive as the 1st hard drve. Then F10 and yes to save changes. Your compter will reboot agin. Then when the Lenovo Logo POST Screen appers on reboot hit F4 to enter the BIOS FLASHING program. The USB Thumb Drive will be seen as the C drive \in the list on the Left, Select it. Then \select the .ROM \file \in the list on the Right and start the BIOS FLASH. \(NOTE Your hart may stop beating... This is normal) Pray to any God you know of and your computer should restart just like normal. Hit F2 and the BIOS will now stay it is 06CN29WW. You will need to \set the boot order to the way you like it and other things \if you need to because they have been changed to the default."
    fi
    echo ""
    echo "End of script"
    Last edited by hunterthomson (2008-08-10 11:17:47)

    Personally.....  (this is just how I would have written it - if it works, then it's good enough for me though )
    I would change this whole block:
    verify="n"
    while [ "$verify" != y ]
    do
    printf "Do you have mbr installed... yes or no?"
    read AN1
    echo ""
    printf "You answered... $AN1 I have installed mbr. Is this correct... y or n?"
    read verify
    done
    echo ""
    if [ "$AN1" == "no" ]
    then
    echo "Install mbr now. Then run this script agin"
    exit
    else
    echo "contunuing script"
    fi
    To this much shorter code:
    MBR='/usr/bin/install-mbr' # Or where ever you expect it to be
    if [ ! -x $MBR ] ; then
    echo "mbr doesn't appear to be installed."
    echo "If it is installed, check it's location, make sure it's executable and then make sure the MBR variable in this script is correct"
    exit 1
    fi
    I wouldn't have used the checkXX variables for each stage:
    mkdir ~/usbbiosfiles
    if [ $? != 0 ] ; then
    #failed
    echo "Could not \make directory usbbiosfiles"
    echo "look above \for \info"
    echo "Fix the problem and run this scrip agin"
    exit 1
    else
    echo "Made directory usbbiosfiles... OK"
    fi
    There is an issue with the way you do your verifications - the user can never get out unless they answer 'y' or hit CTRL+C. Something like this gives them options:
    verify="n"
    while [ "$verify" != "y" && "$verify" != "n" ]; do
    echo "You need to answer 'y'es or 'n'o"
    read verify
    echo $verify | tr "[:upper:]" "[:lower:]" # This converts the answer to lowercase so replies entered in upper case will still work
    done
    if [ $verify != 'y' ] ; then
    exit 1
    fi
    One last thing I try to do in scripts... Declare all your binaries as variables at the start of the program, then execute the binary program by using the variable. For example:
    # Binaries
    TAR='/bin/tar'
    CP='/bin/cp'
    CHMOD='/bin/chmod'
    # Execute tar and chmod the created file
    $TAR cvzf /tmp/tarfile.tar.gz /etc/*.conf
    $CHMOD 400 /etc/*.conf
    This way, it's easy to change the path in future without having to hunt through the script if the paths change, and it also ensures you're calling the programs using the full paths to make sure you're not executing some strange variant or alias that someone has setup. If I use `chmod` 30 times in a script, and the path changes in the future or on a different system (`chmod` is a bad example cause it's highly unlikely to change, but you know what I mean), then all you need to do is update the variable at the start of the script, and it all works again without having to script-hunt and change it 30 times.

  • Bash script to pseudo multithread a encode job lame

    Conceptually, I don't see why a bash script couldn't run x simultaneous lame mp3 encodes where x is the number of cores the user selects.  I just don't know how to go about doing it.  Would it make sense to read in all the .wav files to an array, then divide the array into x sub arrays and feed the work out or is there a more simplistic method?
    EDIT: I found this blog entry but I don't fully understand it. 
    Here is my adaptation of his code:
    #!/bin/bash
    # the number of cores you have on your system
    cores=4
    encode() {
    for file; do
    fileout=$(echo "$file" | sed s'/.wav//')
    lame -V 2 "$file" "$fileout".mp3; done
    export -f encode
    find . -name '*.wav' -print0 | xargs -0 -n 1 -P $cores bash -c 'encode "$@"' --
    Can someone explain to me what the last bit does: 'encode"$@"' --
    Last edited by graysky (2010-03-01 22:17:13)

    The last bit calls the encoide function, passing in all the arguments as past to it on stdin.
    'encode "$@"' calls encode and passes it its arguments (as passed to it from the find command).
    -- tells xargs that there are no more command line options, and to interpret anything "-" as part of the file names.
    man find and man xargs for more info.
    The "--" I'm not sure which man page it'll be in but I think it's a GNU thing?

  • Writing to mplayer's stdin from bash script.

    I was just fulling with some bash script in order to automate the listening of my favorite radio stations via mplayer and a bash script. Going through the mplayers manual I saw the option -slave.
    -slave
    This option switches on slave mode. This is intended for use of MPlayer as a backend to other programs. Instead of intercepting keyboard events, MPlayer will read simplistic command lines from its stdin. The section SLAVE MODE PROTOCOL explains the syntax.
    At first I thought "ok, easy". I made some tries like "mplayer -slave -quiet .... < /tmp/stdin &" and then something like "echo -e 'mute' > /tmp/stdin" but it wouldn't work.
    Is it possible to send a process to the background inside a bash script and then write to it's stdin?
    SLAVE MODE PROTOCOL
    If the -slave option is given, playback is controlled by a line-based protocol. Each line must contain one command otherwise one of the following tokens:
    Commands
    seek <value> [type=<0/:1/:2>]
    Seek to some place in the movie. Type 0 is a relative seek of +/:- <value> seconds. Type 1 seek to <value> % in the movie. Type 2 is a seek to an absolute position of <value> seconds.
    audio_delay <value>
    Adjust the audio delay of value seconds
    quit
    Quit MPlayer
    pause
    Pause/:unpause the playback
    grap_frames
    Somebody know ?
    pt_step <value> [force=<value>]
    Go to next/:previous entry in the playtree.
    pt_up_step <value> [force=<value>]
    Like pt_step but it jumps to next/:previous in the parent list.
    alt_src_step <value>
    When more than one source is available it selects the next/:previous one (only supported by asx playlist).
    sub_delay <value> [abs=<value>]
    Adjust the subtitles delay of +/:- <value> seconds or set it to <value> seconds when abs is non zero.
    osd [level=<value>]
    Toggle osd mode or set it to level when level > 0.
    volume <dir>
    Increase/:decrease volume
    [contrast|brightness|hue|saturation] <-100-100> [abs=<value>]
    Set/:Adjust video parameters.
    frame_drop [type=<value>]
    Toggle/:Set frame dropping mode.
    sub_visibility
    Toggle subtitle visibility.
    sub_pos <value>
    Adjust subtitles position.
    vo_fullscreen
    Switch to fullscreen mode.
    tv_step_channel <dir>
    Select next/:previous tv channel.
    tv_step_norm
    Change TV norm.
    tv_step_chanlist
    Change channel list.
    gui_[loadsubtitle|about|play|stop]

    FIFO's are awesome and can be (ab)used for a lot of cool stuff.
    I've written some applications that do just what you are trying to do ( http://github.com/trapd00r/rmcd and http://github.com/trapd00r/RPD ), if you need inspiration.
    As for the backgrounding - you want to make a 'daemon', to detach from the running shell. See man fork, man 3 setsid and man 3 wait / man 3 waitpid (or my daemonize() function).

  • Simple Mencoder Bash Script

    I have an old PC that I use to play videos using mplayer. However, for some reason the graphics card can't handle a width resolution of more than 768 and I have a lot of hi-def videos. I currently have a .bashrc alias that converts the file and then I play it with mplayer using a second command (all over ssh of course :-P) but I would really like to have it all automated so I can type "play file.avi" and it'll convert and then play the file. Here are the commands I currently run:
    mencoder [file] -ovc lavc -oac pcm -vf scale=768:432 -o [outputfile]
    DISPLAY=:0 mplayer -cache 16384 -fs
    Does anyone have a similar script that they can share or help me write one that does this?
    Thanks
    rocktorrentz

    Since I'm only learning bash scripting at the moment I took this as an opportunity to experiment with some things.  Here is a maxi (probably an overkill) version of the script.  It allows you to specify the directory where you want the converted file saved and after playback it asks if you want to delete the converted file or not.  It also allows you to specify mplayer and mencoder options to be used for conversion and playback.  I'm not sure if you'll find it useful, but I'll post it anyways.  If anyone has any comments or criticisms please let me know.
    #!/bin/sh
    # ****Configuration****
    # Enter the save directory here; if there is no value here the converted file
    # will be saved in the source directory. The correct format is "/aaa/bbb" --
    # leave the final slash out. Other options should be self-explanatory.
    SAVEDIR=""
    MENCODER_OPTIONS="-ovc lavc -oac pcm -vf scale=384:216"
    MPLAYER_OPTIONS="-fs -ao alsa"
    # ****End of configuration****
    # Other variables
    EXTENSION="${1##*.}"
    SCALED="${1%.$EXTENSION}_scaled.$EXTENSION"
    SCALED_SAVEDIR="$SAVEDIR/`basename "$SCALED"`"
    # Check if the SAVEDIR exists
    if [ ! -z $SAVEDIR ] && [ ! -d "$SAVEDIR" ]
    then
    echo "$SAVEDIR does not exist or is not a directory. Exiting...";
    exit 1
    fi
    # Play if converted file already exists, otherwise play after converting
    if [ -z "$SAVEDIR" ]
    then
    if [ -f "$SCALED" ]
    then
    DISPLAY=:0 mplayer $MPLAYER_OPTIONS "$SCALED"
    else
    mencoder "$1" $MENCODER_OPTIONS -o "$SCALED"
    DISPLAY=:0 mplayer $MPLAYER_OPTIONS "$SCALED"
    fi
    else
    if [ -f "$SCALED_SAVEDIR" ]
    then
    DISPLAY=:0 mplayer $MPLAYER_OPTIONS "$SCALED_SAVEDIR"
    else
    mencoder "$1" $MENCODER_OPTIONS -o "$SCALED_SAVEDIR"
    DISPLAY=:0 mplayer $MPLAYER_OPTIONS "$SCALED_SAVEDIR"
    fi
    fi
    # After playback is done ask if the file should be deleted
    while true
    do
    echo -n "Would you like to delete the converted file? (y or n) "
    read CONFIRM
    case $CONFIRM in
    y|Y|YES|yes|Yes)
    break
    n|N|no|NO|No)
    echo "You entered \"$CONFIRM\" -- the converted file will not be deleted."
    exit
    echo "Please enter only y or n"
    esac
    done
    # Option to delete file was selected
    echo "You entered \"$CONFIRM\" -- deleting the converted file."
    if [ -z "$SAVEDIR" ]
    then
    rm "$SCALED"
    else
    rm "$SCALED_SAVEDIR"
    fi

  • Passing Files/Folders to BASH script...

    I'm trying to pass a list of files and folders selected in finder to a bash script so that I can use VLC to perform some transcoding and concatenation on them.
    I'm using "Get Selected Finder Items" to pass the "Files/Folders" output "As Arguments" to my script.
    Problem is with spaces in the filenames. Apparently Automator delimits the list of files with spaces. So I have spaces in the filenames and spaces between the files. So my bash script just sees a list like this:
    /Users/johnt/Documents/3rd Party Audio For Conversion/WFWC - 3.6.2009 3.7.2009/01c Director Report March 6 2009.wav /Users/johnt/Documents/3rd Party Audio For Conversion/WFWC - 3.6.2009 3.7.2009/01b Comm Disc Mar 6 2009.wav
    ...with no way to differentiate each file. Is there a way to tell automator to escape the spaces in the file paths so that my loop doesn't try to run through $@ as:
    /Users/johnt/Documents/3rd
    Party
    Audio
    for
    ... etc etc
    Thanks

    Thanks Neil, that was helpful. I'll play with that AppleScript and see what happens.
    I figured this was better suited in the Automator forum since I'm trying to format the output of what Finder sends before it ever hits the Bash script. My Bash script itself has no problem, so I didn't see any point going over to the UNIX forums.
    You gotta love the ability of OSX to be able to handle all sorts of technologies and integrate them well. Apparently, there's nothing Apple can do to make it's users do the same thing.

  • SQLPlus output within bash script

    Hey everyone, I wasn't sure if this should go here or in the SQL forum or the Linux forum, but here goes:
    Using Oracle10g on Linux, I'm using a bash script to run an sql script, but when I try to echo the results, it shows the output in a single line.
    Here's the script
    USERLIST=`sqlplus -s  / AS SYSDBA <<EOF
       set head off
       set verify off
       set feedback off
       SELECT username from dba_users;
       exit;
    EOF
    `
    echo $USERLIST;And here's the output:
    oracle@apps scripts]$ ./userl.sh
    PAYROLL HR2 CORE DEMO TIMEKEEPING SYS EXPENSE Is there anyway so that the output can be shown with line breaks, where all the output is not on one line? I understand I can spool to a file using the spool command, however I'd like to try and get it working this way first.
    Any help would be much appreciated, thanks.
    Edited by: oscrub on Sep 22, 2010 6:46 PM

    Handle:      oscrub
    Status Level:      Newbie
    Registered:      Oct 5, 2008
    Total Posts:      7
    Total Questions:      4 (3 unresolved)
    so many questions & so few answers.
    sh  t.sh
    SYSTEM
    SYS
    MGMT_VIEW
    DBSNMP
    SYSMAN
    USER1
    DBADMIN
    HR
    OE
    SH
    BONGO
    SCOTT
    OUTLN
    OLAPSYS
    SI_INFORMTN_SCHEMA
    OWBSYS
    ORDPLUGINS
    XDB
    ANONYMOUS
    CTXSYS
    ORDDATA
    OWBSYS_AUDIT
    APEX_030200
    APPQOSSYS
    WMSYS
    EXFSYS
    ORDSYS
    MDSYS
    FLOWS_FILES
    SPATIAL_WFS_ADMIN_USR
    SPATIAL_CSW_ADMIN_USR
    APEX_PUBLIC_USER
    DIP
    IX
    MDDATA
    PM
    BI
    XS$NULL
    ORACLE_OCMHow do you spell S-Q-L?

  • Download Bash script running from Task-bar folder

    Hi, Not sure why but when Im trying to open my Downloads file from the task bar its openning up on my desktop as "Downloads-Bash script! how do i stop this please. Its the same if I open from Finder.
    Thank you all in anticipation of a resolve.

    Enter the following command in a Terminal window by copying or dragging (don’t type):
    xattr -c ~/Downloads
    Press return. You can then quit Terminal. Try the action again. If the same thing happens, relaunch the Finder by selecting
     ▹ Force Quit ▹ Finder
    and pressing return or clicking Relaunch.

  • Nifty scroll script still not fast enough

    I started writing this python script because I wanted to have a scrolling, fixed-width mpc status line in my dwm top bar:
    #!/usr/bin/python3
    from time import time
    from subprocess import getstatusoutput
    import sys
    _ERROR_MSG = "Usage: scrollout [-l (int)] (cmd)"
    def input_cmd(cmd,l):
    if cmd == "":
    s = sys.stdin.read()
    else:
    e,s = getstatusoutput(cmd)
    if e: sys.exit(1)
    s = s.replace("\n"," ")
    s += (" " * int(l/3))
    k = len(s)
    t = int(k*(time()/k-int(time()/k)))
    if k <= l: # static
    return s
    else: # scrolling
    while len(s[t:]) < l: s += s
    return s[t:t+l]
    def run():
    _arg = -1
    length = 20
    cmd = ""
    enter_cmd = False
    flags = ("-l")
    for arg in sys.argv[1:]:
    if enter_cmd or (arg not in flags and _arg not in flags):
    cmd += arg + " "
    enter_cmd = True
    elif _arg == "-l":
    try:
    length = int(arg)
    except:
    print(_ERROR_MSG)
    exit(1)
    _arg = arg
    output=input_cmd(cmd,length)
    print(output)
    run()
    Since it uses time since Epoch to determine how much to scroll the text at any given moment it doesn't have to have any internal loops or run any longer than it takes to compute the output. You can simply call it like so:
    scrollout -l 20 mpc current
    alternatively
    mpc current | scrollout -l 20
    For example, in my statusbar script I have the following line:
    mpc_status="|$(scrollout -l 20 mpc current) ($(mpc | grep -Eo '[0-9]*\:[0-9]*\/[0-9]*\:[0-9]*')) "
    I find it works nicely, but is a bit slow. Not surprisingly, since it has to re-import all of it's libraries every time it gets launched. To be a truly useful script I imagine it would have to be able to finish it's task in less than one second. Right now it's just above that, ofcourse somewhat depending on what command is being piped through it. The big timestealer, however, is the module imports (according to the python profiler). Having a pretty limited experience of programming, I would like to know if anyone knows of a good workaround for this. Perhaps some way to speed up the module imports or to mimic some of the functionality of these modules without having to import them?
    Cheers,
    Mach

    Thanks a lot guys! Glad to see such enthusiasm. :-)
    juster: But I don't know C! :-) Oh well, I'm working nights, so I have time to learn.
    Rewrote the script in python based on juster's algorithm:
    #!/usr/bin/python3
    from time import time
    import sys
    w = 20
    if len(sys.argv) > 1: w = sys.argv[1]
    s = sys.stdin.read().replace("\n","") + (" " * int(w/3))
    if len(s) > w:
    i = int(time() % w)
    while len(s[i:]) < w: s += s
    s = s[i:i+w]
    print(s)
    Then wrote a small bash script to run each of the different variants a hundred times and output their average execution time. Brace yourselves...
    The script originally posted:
    # mpc current | runtime10 scrollout.py | grep nanoseconds
    Average run time: 0 seconds (205726798 nanoseconds)
    Roughly the same script, frozen with cx_freeze:
    # mpc current | runtime10 scrollout | grep nanoseconds
    Average run time: 0 seconds (166651145 nanoseconds)
    The perl script submitted by juster:
    # mpc current | runtime10 ./perlscrollout | grep nanoseconds
    Average run time: 0 seconds (24679770 nanoseconds)
    The python script from this post:
    # mpc current | runtime10 ./pythonscrollout | grep nanoseconds
    Average run time: 0 seconds (190167249 nanoseconds)
    So, the perl script still clearly stands out. Also, the new python script doesn't stand a chance compared to the old frozen executable, even though the script itself is proven faster than the original one. A frozen version of the new script will only get me so far in optimization - obviously, this is not a job for python.
    Anyone care to prove me wrong?

  • Bash scripts with rox

    in rox-filer you can "send" files to bash scripts by right clicking on them and selecting the script.  for example:
    mogrify -format jpg $1
    i use these scripts all the time and they are really handy but they are limited.
    $1 uses the whole path and filename so it is almost impossible to do simple renaming or copy a file to a server without it being copied to /targetdir/fullpath/filename, for example.
    I am trying to work out how to get the filename into my scripts - with the full path - and then chop it up into path, filename, extention.  i read about word modifiers in bash e.g. !$:h - which works great on the command line but not in scripts - any ideas?

    You mean dirname, basename commands?
    This should be what you are looking for (I hope):
    http://www.splike.com/howtos/bash_faq.html

  • New to bash scripting; making script to change laptop CPU governor

    I've got an old laptop and I like to be able to change the governor between performance and ondemand depending on whether or not I've got the laptop plugged in. I'd really like to be able to do this from a shortcut on the desktop, so I decided to try making a bash script that used Zenity dialogs to accomplish this.
    I think it turned out pretty much how I'd like, however the error handling on getting the root password authenticated is pretty broken. I'm not sure how exactly I should go about it.. I think that the long timeout that occurs when you enter a wrong password for su is causing problems. Is there a better way of doing this? I don't use sudo, and I'd really prefer to avoid it and stick to using su if at all possible.
    #!/bin/bash
    #This script will supply a Zenity dialog with the option to change the laptop's governor.
    #It will use a Zenity dialog to acquire the root password from user for autorization to change the governor.
    #Set up some variables we will use.
    optionPerformance="FALSE"
    optionOndemand="FALSE"
    #Read the current state of the governor.
    currentGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
    #Change the variables we previously set up to reflect current state of governor. This will be used to determine which option is pre-selected in the Zenity dialog we will create.
    if [ $currentGovernor = 'performance' ]
    then optionPerformance="TRUE"
    fi
    if [ $currentGovernor = 'ondemand' ]
    then opitonOndemand="TRUE"
    fi
    #Set up Zenity dialog which allows user to select the governor they want active. The currently active governor will be selected by default.
    #User's input will go to the wantedGovernor variable for future use.
    wantedGovernor=$(zenity --list --text "Select which governor you want to make active:" --radiolist --column "" --column "Options" $optionPerformance "performance" $optionOndemand "ondemand")
    #Check to see if user clicked Cancel button.
    if [ $? = 1 ]
    then exit 0
    fi
    #Did user select the already active profile? If so, simply report that and exit.
    if [ $wantedGovernor = $currentGovernor ]
    then
    newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
    zenity --info --text "Governor is already set to $newGovernor.\n\nNo changes were made."
    exit 0
    fi
    #Now that we know what the user wants, let's do it.
    #We will use cpupower to change the governor. This will require root privileges, so we will use Zenity to get the root password from user and pipe it into su. (Is this the best way?)
    zenity --title "Password for root:" --password | su -c "cpupower frequency-set -g $wantedGovernor"
    #Check to see if user clicked Cancel button.
    if [ ${PIPESTATUS[0]} = 1 ]
    then exit 0
    fi
    #Check to see if user entered incorrect root password.
    if [ ${PIPESTATUS[1]} = 1 ]
    then
    zenity --error --text "Incorrect root password.";
    exit 1
    fi
    #Now that we've made the change, let's check the current state of the governor again so that we can report it to the user and they can verify success.
    newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
    zenity --info --text "Governor is now set to $newGovernor."
    Last edited by gilmoreja (2015-01-26 21:49:19)

    Thanks for the advice, Awebb. I looked into gksu but I didn't like how it offered to save the root password in gnome-keyring. I found an alternative, ktsuss, and decided to go with that instead.
    I'll post the finished script here, for anyone who is ever interested in such a thing:
    #!/bin/bash
    #This script will supply a Zenity dialog with the option to change the laptop's governor.
    #It will use a Zenity dialog to acquire the root password from user for autorization to change the governor.
    #Set up some variables we will use.
    optionPerformance="FALSE"
    optionOndemand="FALSE"
    #Read the current state of the governor.
    currentGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
    #Change the variables we previously set up to reflect current state of governor. This will be used to determine which option is pre-selected in the Zenity dialog we will create.
    if [ $currentGovernor = 'performance' ]
    then
    optionPerformance="TRUE"
    fi
    if [ $currentGovernor = 'ondemand' ]
    then optionOndemand="TRUE"
    fi
    #Set up Zenity dialog which allows user to select the governor they want active. The currently active governor will be selected by default.
    #User's input will go to the wantedGovernor variable for future use.
    wantedGovernor=$(zenity --list --text "Select which governor you want to make active:" --radiolist --column "" --column "Options" $optionPerformance "performance" $optionOndemand "ondemand")
    #Check to see if user clicked Cancel button.
    if [ $? = 1 ]
    then exit 0
    fi
    #Did user select the already active profile? If so, simply report that and exit.
    if [ $wantedGovernor = $currentGovernor ]
    then
    newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
    zenity --info --text "Governor is already set to $newGovernor.\n\nNo changes were made."
    exit 0
    fi
    #Now that we know what the user wants, let's do it.
    #We will use cpupower to change the governor. This will require root privileges, so we will use ktsuss to get that.
    ktsuss cpupower frequency-set -g $wantedGovernor
    #Now that we've made the change, let's check the current state of the governor again so that we can report it to the user and they can verify success.
    newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
    zenity --info --text "Governor is now set to $newGovernor."

  • Why does do shell work differntly from running the same bash script in terminal?

    i have the following a/s:
    set scriptPath to quoted form of ((POSIX path of (path to me)) & lnThumb)       set ftn to ""       repeat            try                 do shell script scriptPath & " " & ppath & " " & ftn                 exit repeat            on error error_message number error_number                  if error_number is not -128 then                      set ftn to (choose file with prompt "select folder thumbnail" default location dir without invisibles)                      set ftn to quoted form of the POSIX path of ftn                 end if            end try       end repeat
    calling this bash script:
    #!/bin/bash -f   cd "$1"  rm ./folderthumb.jpg   if [ $# -gt 1 ]  then      ft=${2/#"$1"\//}  else      ft=$(awk '/folderIcon=/{printf("%s",$1)}' meta.properties  | sed s/folderIcon=// )      if [ 0$ft -eq 0 ]       then          exit 1      fi      ft="thumbs/"$ft  fi  ln -s $ft ./folderthumb.jpg  exit 0
    which works as expected when run from the cli:
    tomw> /Applications/imageProc/fixJAlbum.app/Contents/Resources/Scripts/lnThumb.sh `pwd` `pwd`/thumbs/P1040161.JPG   tomw> ls -l folderthumb.jpg lrwxr-xr-x  1 tomw  admin  19 Oct 22 10:36 folderthumb.jpg -> thumbs/P1040161.JPG
    but fails to strip the common directory when called from do shell:
    tomw> ls -l folderthumb.jpg   lrwxr-xr-x  1 tomw  admin  89 Oct 22 10:36 folderthumb.jpg -> /Users/tomw/Desktop/trip2albequerque/albequerque/oldRailyards2nobHill/thumbs/P1 040133.JPG
    w-t-f???

    Click on the "Use Advanced editor" on the upper Right of the edit box.
    Select the text you want preserved
    Click on the >> icon then select "Syntax Highlighting" -> "Plain"
    And you will get this
       kind of
    output    when    you     post

  • [SOLVED] XMMS2 media hotkeys, bash scripts

    Hi!
    For the really beginners of the XMMS2 users as me, should be a nice something like a guide/tutorial.
    Here is the bash scripts that might enchant functionality and be more useful for use of the media keys.
    For randomizing before any other action you can use even something like:
    xmms2 playlist shuffle ; xmms2 jump 1; xmms2 play
    # Just for dummies
    The Preview hotkey loop.
    From the begin of the playlist to the end of it when current is the first one being played:
    #!/bin/bash
    #Play the previews or first if end of the playlist
    if [ "XX"$(xmms2 prev | awk '{print $1}') == "XXServer" ] ; then
    if [ "XX"$(xmms2 jump $(xmms2 list | grep -i '/' |wc -l) | awk '{print $1}') == "XXServer" ] ; then
    xmms2 playlist list;
    echo The playlist is empty, please choose one from of the above ;
    echo or add a new songs to the playlist with a '"xmms2 add"';
    fi; fi;
    #It takes time to count to the last song in the playlist, longer it is more time it takes :(. I haven't found a better way yet.
    The Next hotkey loop.
    When the end of the playlist is reached then goto jumping to the first one song in the playlist:
    #!/bin/bash
    #Play the first song if in the end of the playlist
    if [ "XX"$(xmms2 next | awk '{print $1}') == "XXServer" ] ; then
    if [ "XX"$(xmms2 jump 1 | awk '{print $1}') == "XXServer" ] ; then
    xmms2 playlist list;
    echo The playlist is empty, please choose one from of the above ;
    echo or add a new songs to the playlist with a '"xmms2 add"';
    fi; fi;
    For the Play/Pause key:
    #!/bin/bash
    #For the single Play/Pause key
    GetStatus=$(xmms2 current | awk -F":" '{print $1}')
    #Any command line parameters to the script for randomizing of the playslist.
    if [ "S" != "S"$1 ] ; then
    xmms2 playlist shuffle
    fi;
    if [ "$GetStatus" == "Playing" ]; then xmms2 pause;fi
    if [ "$GetStatus" == "Paused" ]; then xmms2 play;fi
    if [ "$GetStatus" == "Stopped" ]; then
    xmms2 play
    GetStatus=$(xmms2 current | awk -F":" '{print $1}')
    if [ "$GetStatus" == "Stopped" ]; then
    xmms2 playlist list;
    echo The playlist is empty, please choose one from of the above ;
    echo or add a new songs to the playlist with a '"xmms2 add"';
    fi
    fi
    or you can use even xmms2 toggle command line for the play/pause hotkey.
    Turn On/Off repeat/loop of the playlist:
    #!/bin/bash
    GetStatus=$(xmms2 server config playlist.repeat_all )
    case $GetStatus in
    "playlist.repeat_all = 1") xmms2 server config playlist.repeat_all 0 ; sudo beep; echo is OFF ;;
    "playlist.repeat_all = 0") xmms2 server config playlist.repeat_all 1 ; sudo beep ; sudo beep ; echo is ON;;
    esac
    You can install beep but the beep has a problem, you can run it only as a root but a more danger way is to by pass this by adding the beep into /etc/sudoers , e.g. yourusername ALL=NOPASSWD: /usr/sbin/beep.  Be careful! It may expose your system for unwanted access to and do a harm. The best way is to find a better way for notification of changes.
    If someone has another script solutions for the multimedia hotkeys or media fun for XMMS2 then please share with us!
    Automation is power of the shell
    Notice
    The hotkey names of my Digital Media Keyboard 3000, but I think that it becomes more as a standard, it is just to get a faster access to the names.
    XF86AudioPlay, XF86AudioNext, XF86AudioPrev,XF86AudioStop
    XF86AudioMute (amixer -c 0 set Master toggle), *, (pactl set-sink-mute 0 toggle)
    XF86AudioRaiseVolume (amixer -c 0 set Master 3+), xmms2 server volume +3, (pactl set-sink-volume 0 +3%)
    XF86AudioLowerVolume (amixer -c 0 set Master 3-). xmms2 server volume -3, (pactl set-sink-volume 0 -- -3%)
    amixer = ALSA
    pactl = PulseAudio (0 is index of the sinks, you can see which you can use with pacmd list-sinks, marked with * is default)
    The other way to increase and decrease volumes is here.
    Change between ALSA and PulseAudio sound servers for XMMS2
    nyxmms2 server config output.plugin pulse
    nyxmms2 server config output.plugin alsa
    Otherwise you can use xev to retrieve the names of the supported keys by X server, as I know X server has a limitations to the 255 key numbers/keycodes. One more but less useful for GUI is showkey, just to know that it is also and always exists, with a great manual about the kbd keys.
    * To mute/unmute XMMS2 you can use xmms2 server volume 0 / xmms2 server volume 100 or for more advanced e.g. xmms2 server volume -c left 100/xmms2 server volume -c right 100 and combine with any keys you wish the way is best for you. I haven't found any way to make anything to remember status after mute/unmute of xmms2. Alias for the mute only is xmms2 mute. If you will find it before me please help .
    Here is one more guide for the BlackBox menu. I could not get xmms2 mlib loadall to work in Arch.
    In Arch you must use xmms2 playlist sort instead of xmms2 sort because it doesn't work otherwise.
    xmms2 playlist sort album
    xmms2 playlist sort title
    xmms2 playlist sort artis
    Last edited by Andy_Crowd (2014-10-18 11:34:45)

    Zariel wrote:
    i guess something like this?
    %optical ALL=(ALL) NOPASSWD: ALL
    I found the clues for this in the sudoers manual:
    handy   ALL = NOPASSWD: /sbin/umount /CDROM,\
                    /sbin/mount -o nosuid\,nodev /dev/cd0a /CDROM
    Which works in so far as now mounting no longer needs the password.
    Which leaves me with the problem of trying to understand how to get Worker to mount the optical drive on command.
    If I enter the bash command in the Terminal as follows:
    mount /mnt/dvd
    the media is mounted, after which I can push the button in Worker, which I have configured with:
    /mnt/dvd
    & the root list of the optical media is displayed in the active panel of Worker.
    I just haven't been able to get Worker to use "mount /mnt/dvd" yet, there will be a way, I wonder how long it will take me to find it? lol
    Last edited by handy (2008-11-19 06:48:09)

Maybe you are looking for