Udev bash script for autodialing usb huawei modem

Hey
I've got an interesting one here.
I have scripted up a bash script to be triggered by a udev add event for my usb modem. As far as I can tell the udev event is firing correctly according to udevadm.
ACTION=="add", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1003", RUN+="/bin/sh /usr/local/bin/huawei_key.sh add"
ACTION=="remove", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1003", RUN+="/bin/sh /usr/local/bin/huawei_key.sh remove"
And heres the code from the script
#!/bin/bash
#returns
# 0 Successfully ran script for case
# 1 wvdial process already running
# 2 wvdial was not terminated
# 3 script was not ran with ADD or REMOVE events
function getpid #get process id of running program
pidof wvdial
if [ "$?" = 0 ];
then
pid=`pidof wvdial`
running=1
else
running=0
fi
function checkrun #check for a running copy of the program
pidof wvdial
if [ "$?" == "0" ];
then
running=1
else
running=0
fi
function killloop #a set of time kill commands to let the program exit gracefully
#two terms, one int and one kill with suitable gaps
getpid
checkrun
if [ "$running" = "0" ];
then
return
fi
kill $pid
sleep 10
checkrun
if [ "$running" = "0" ];
then
return
fi
kill $pid
sleep 10
checkrun
if [ "$running" = "0" ];
then
return
fi
kill -INT $pid
sleep 5
checkrun
if [ "$running" = "0" ];
then
return
fi
kill -KILL $pid
sleep 5
checkrun
if [ "$running" = "1" ];
then
exit 2 #process fails to die
fi
function getlaststatus
if [ -e "/var/run/huawie" ];
then
last=`cat /var/run/huawie`
else
last=0
fi
if [ "$1" = "add" ];
then
getlaststatus
if [ "$last" = "1" ];
then
exit 1
fi
echo 1 > /var/run/huawie #block future udev events
getpid
if [ "$running" = "1" ];
then
exit 1
fi
modprobe usbserial
sleep 6 #modem init time
wvdial &
exit 0
elif [ "$1" = "remove" ];
then
getlaststatus
if [ "$last" = "2" ];
then
exit 0
fi
echo 2 > /var/run/huawie
killloop
exit 0
else
echo 3 > /var/run/huawie
exit 3
fi
I'd appreciate any ideas, this one has me stumped
Edit:
Forgot to add that when I call the script manually it works like a charm.
Last edited by adamd (2009-08-25 15:04:06)

Hey
I've got an interesting one here.
I have scripted up a bash script to be triggered by a udev add event for my usb modem. As far as I can tell the udev event is firing correctly according to udevadm.
ACTION=="add", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1003", RUN+="/bin/sh /usr/local/bin/huawei_key.sh add"
ACTION=="remove", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1003", RUN+="/bin/sh /usr/local/bin/huawei_key.sh remove"
And heres the code from the script
#!/bin/bash
#returns
# 0 Successfully ran script for case
# 1 wvdial process already running
# 2 wvdial was not terminated
# 3 script was not ran with ADD or REMOVE events
function getpid #get process id of running program
pidof wvdial
if [ "$?" = 0 ];
then
pid=`pidof wvdial`
running=1
else
running=0
fi
function checkrun #check for a running copy of the program
pidof wvdial
if [ "$?" == "0" ];
then
running=1
else
running=0
fi
function killloop #a set of time kill commands to let the program exit gracefully
#two terms, one int and one kill with suitable gaps
getpid
checkrun
if [ "$running" = "0" ];
then
return
fi
kill $pid
sleep 10
checkrun
if [ "$running" = "0" ];
then
return
fi
kill $pid
sleep 10
checkrun
if [ "$running" = "0" ];
then
return
fi
kill -INT $pid
sleep 5
checkrun
if [ "$running" = "0" ];
then
return
fi
kill -KILL $pid
sleep 5
checkrun
if [ "$running" = "1" ];
then
exit 2 #process fails to die
fi
function getlaststatus
if [ -e "/var/run/huawie" ];
then
last=`cat /var/run/huawie`
else
last=0
fi
if [ "$1" = "add" ];
then
getlaststatus
if [ "$last" = "1" ];
then
exit 1
fi
echo 1 > /var/run/huawie #block future udev events
getpid
if [ "$running" = "1" ];
then
exit 1
fi
modprobe usbserial
sleep 6 #modem init time
wvdial &
exit 0
elif [ "$1" = "remove" ];
then
getlaststatus
if [ "$last" = "2" ];
then
exit 0
fi
echo 2 > /var/run/huawie
killloop
exit 0
else
echo 3 > /var/run/huawie
exit 3
fi
I'd appreciate any ideas, this one has me stumped
Edit:
Forgot to add that when I call the script manually it works like a charm.
Last edited by adamd (2009-08-25 15:04:06)

Similar Messages

  • [solved]Need help with a bash script for MOC conky artwork.

    I need some help with a bash script for displaying artwork from MOC.
    Music folders have a file called 'front.jpg' in them, so I need to pull the current directory from MOCP and then display the 'front.jpg' file in conky.
    mocp -Q %file
    gives me the current file playing, but I need the directory (perhaps some way to use only everything after the last  '/'?)
    A point in the right direction would be appreciated.
    thanks, d
    Last edited by dgz (2013-08-29 21:24:28)

    Xyne wrote:
    You should also quote the variables and output in double quotes to make the code robust, e.g.
    filename="$(mocp -Q %file)"
    dirname="${filename%/*}"
    cp "$dirname"/front.jpg ~/backup/art.jpg
    Without the quotes, whitespace will break the code. Even if you don't expect whitespace in any of the paths, it's still good coding practice to include the quotes imo.
    thanks for the tip.
    here it is, anyhow:
    #!/bin/bash
    filename=$(mocp -Q %file)
    dirname=${filename%/*}
    cp ${dirname}/front.jpg ~/backup/art.jpg
    then in conky:
    $alignr${execi 30 ~/bin/artc}${image ~/backup/art.jpg -s 100x100 -p -3,60}
    thanks for the help.
    Last edited by dgz (2013-08-29 21:26:32)

  • Bash script for checking link status

    So I'm doing some SEO work I've been tasked with checking a couple hundred thousand back links for quality.  I found myself spending a lot of time navigating to sites that no longer existed.  I figured I would make a bash script that checks if the links are active first.  The problem is my script is slower than evolution.  I'm no bash guru or anything so I figured maybe I would see if there are some optimizations you folks can think of.  Here is what I am working with:
    #!/bin/bash
    while read line
    do
    #pull page source and grep for domain
    curl -s "$line" | grep "example.com"
    if [[ $? -eq 0 ]]
    then
    echo \"$line\",\"link active\" >> csv.csv else
    echo \"$line\",\"REMOVED\" >> csv.csv
    fi
    done < <(cat links.txt)
    Can you guys think of another way of doing this that might be quicker?  I realize the bottleneck is curl (as well as the speed of the remote server/dns servers) and that there isn't really a way around that.  Is there another tool or technique I could use within my script to speed up this process?
    I will still have to go through the active links one by one and analyze by hand but I don't think there is a good way of doing this programmatically that wouldn't consume more time than doing it by hand (if it's even possible).
    Thanks

    I know it's been awhile but I've found myself in need of this yet again.  I've modified Xyne's script a little to work a little more consistently with my data.  The problem I'm running into now is that urllib doesn't accept IRIs.  No surprise there I suppose as it's urllib and not irilib.  Does anyone know of any libraries that will convert an IRI to a URI?  Here is the code I am working with:
    #!/usr/bin/env python3
    from threading import Thread
    from queue import Queue
    from urllib.request import Request, urlopen
    from urllib.error import URLError
    import csv
    import sys
    import argparse
    parser = argparse.ArgumentParser(description='Check list of URLs for existence of link in html')
    parser.add_argument('-d','--domain', help='The domain you would like to search for a link to', required=True)
    parser.add_argument('-i','--input', help='Text file with list of URLs to check', required=True)
    parser.add_argument('-o','--output', help='Named of csv to output results to', required=True)
    parser.add_argument('-v','--verbose', help='Display URLs and statuses in the terminal', required=False, action='store_true')
    ARGS = vars(parser.parse_args())
    INFILE = ARGS['input']
    OUTFILE = ARGS['output']
    DOMAIN = ARGS['domain']
    REMOVED = 'REMOVED'
    EXISTS = 'EXISTS'
    NUMBER_OF_WORKERS = 50
    #Workers
    def worker(input_queue, output_queue):
    while True:
    url = input_queue.get()
    if url is None:
    input_queue.task_done()
    input_queue.put(None)
    break
    request = Request(url)
    try:
    response = urlopen(request)
    html = str(response.read())
    if DOMAIN in html:
    status = EXISTS
    else:
    status = REMOVED
    except URLError:
    status = REMOVED
    output_queue.put((url, status))
    input_queue.task_done()
    #Queues
    input_queue = Queue()
    output_queue = Queue()
    #Create threads
    for i in range(NUMBER_OF_WORKERS):
    t = Thread(target=worker, args=(input_queue, output_queue))
    t.daemon = True
    t.start()
    #Populate input queue
    number_of_urls = 0
    with open(INFILE, 'r') as f:
    for line in f:
    input_queue.put(line.strip())
    number_of_urls += 1
    input_queue.put(None)
    #Write URL and Status to csv file
    with open(OUTFILE, 'a') as f:
    c = csv.writer(f, delimiter=',', quotechar='"')
    for i in range(number_of_urls):
    url, status = output_queue.get()
    if ARGS['verbose']:
    print('{}\n {}'.format(url, status))
    c.writerow((url, status))
    output_queue.task_done()
    input_queue.get()
    input_queue.task_done()
    input_queue.join()
    output_queue.join()
    The problem seems to be when I use urlopen
    response = urlopen(request)
    with a URL like http://www.rafo.co.il/בר-פאלי-p1
    urlopen fails with an error like this:
    Exception in thread Thread-19:
    Traceback (most recent call last):
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 639, in _bootstrap_inner
    self.run()
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 596, in run
    self._target(*self._args, **self._kwargs)
    File "./linkcheck.py", line 35, in worker
    response = urlopen(request)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 160, in urlopen
    return opener.open(url, data, timeout)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 473, in open
    response = self._open(req, data)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 491, in _open
    '_open', req)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 1272, in http_open
    return self.do_open(http.client.HTTPConnection, req)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 1252, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 1049, in request
    self._send_request(method, url, body, headers)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 1077, in _send_request
    self.putrequest(method, url, **skips)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 941, in putrequest
    self._output(request.encode('ascii'))
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-8: ordinal not in range(128)
    I'm not too familiar with how character encoding works so I'm not sure where to start.  What would be a quick and dirty way (if one exists) to get URLs like this to play nicely with python's urlopen?

  • Bash script for apache restart

    I need a way of restarting apache for a user who does not have admin priveleges. My thought is that a bash script could be written to restart apache and would also have the admin password. The permissions would be such that the non-admin user could execute it but not read/write.
    i.e.
    sudo apachectl restart
    ??password??
    I don't know if this is possible because sudo has -p but I didn't see --password
    Mini   Mac OS X (10.4.8)  

    Hi David,
       I've posted about sudo on two threads that are still on page one, Startup permissions change and system.log question. You shouldn't need a password and you can specify exactly who should be able to restart Apache.
       You probably think of sudo as an all-or-nothing solution; either a user can execute anything as root or nothing. Nothing could be closer to the truth. Not only can you specify individual commands but you can specify arguments as well. Thus, you could give someone the right to start or restart Apache but not to stop it. The perfect solution has been created for you; give it a whirl.
    Gary
    ~~~~
       ... an anecdote from IBM's Yorktown Heights Research Center. When a programmer used his new computer terminal, all was fine when he was sitting down, but he couldn't log in to the system when he was standing up. That behavior was 100 percent repeatable: he could always log in when sitting and never when standing.
       Most of us just sit back and marvel at such a story; how could that terminal know whether the poor guy was sitting or standing? Good debuggers, though, know that there has to be a reason. Electrical theories are the easiest to hypothesize: was there a loose wire under the carpet, or problems with static electricity? But electrical problems are rarely consistently reproducible. An alert IBMer finally noticed that the problem was in the terminal's keyboard: the tops of two keys were switched. When the programmer was seated he was a touch typist and the problem went unnoticed, but when he stood he was led astray by hunting and pecking.
             -- "Programming Pearls" column, by Jon Bentley in CACM February 1985

  • Helpful Linux Bash Scripts for I.T. Admins

    I was wondering if you guys had any recommendations for helpful / simple Bash scripts that do helpful tasks in regards to Linux system administration? I have never created or used a Bash shell script but know that many of you guys do. I have no programming experience what so ever so decided to ask if you guys do have one or few scripts that are useful in basic administration tasks, could you please post them or at least point someone who is interested in the right direction?
    Thank you so much!

    I'm no sysadmin but one were to use command-line a lot i would give ZSH a shot. A nicely configured zsh shell can be unbelievably comfortable and is certainly a great tool.
    As for scripts I always thought of them as little helpers customized for certain situations. For instance easing repetitive tasks, batching some steps and timing/automating little things. For general purpose I'd probably look at available software first.
    Maybe tmux for terminal management, ranger for file management, a tiling window manager for efficiency, ssh and other survaillance/maintenance software? Personally, I'd very much like to hear, too, what software/scripts/.. linux systems admins use to keep the work to a minimum .

  • [Solved]Automating a script for a usb device on systemd?

    Solution:See 3rd post by 65kid.
       Ok I'm trying to learn how to automate the execution of a script I wrote to run whenever a specific usb device is plugged in. In this case a usb flash drive with a specific partition identified though UUID following the path /dev/disk/by-uuid/specified-partion's-uuid.
       Basically the script uses rsync to update a snapshot of my system which I made bootable on this device. following the guide given in the wiki on full system backup using rsync I edited the --exclude options to ignore the contents of my /boot/ /etc/fstab and /etc/mkinitcpio.conf since the fstab entries, hooks array and initramfs and kernel images generated with them needed to be changed so as to make this snapshot bootable and adapted for use on the usb stick.
    the ultimate goal is to have a bootable snapshot the can be updated with whatever changes have been made with my system(i.e. pacman -Syu updates,config changes etc...) while leaving out the important things needed to have the usb still bootable afterwards. I've already succeeded at getting the script to work but I have to mount it manually then execute the script myself and I know that it works afterwards as I can still boot from the stick afterwards.
       This is not a question about rsync (which is why the script isn't posted here), to repeat myself, It's about how to execute ANY custom script whenever a specific device is plugged in. More specifically when a storage device with a certain uuid is detected after the device has been plugged in. I believe it may be different for running pure systemd and so that was the reasoning for having it mentioned in the subjects title(if I'm wrong then correct my understanding). If anything a few pointers on where to look would be appreciated. I've been googling and reading the wiki a bit with nothing specific on how to approach this. If an example of the script is requested I'll post it but it's not relevent to my question.
       For a general veiw of my setup regarding external storage volumes I do not automount anything as I do not use all the things I plug in in the same manner. Some of the stuff I do requires them to be unmounted or  mounted to different mount points(specified by me). The script handles the mounting part by itself just fine. The idea I have is to run it automatically when the flash drive is present. Any suggestions?
    Last edited by Thme (2012-12-29 00:06:56)

    Awebb wrote:You "seem to remember" has FUD potential, could you care to find the post again?
    he is probably referring to this: https://bbs.archlinux.org/viewtopic.php … 2#p1113682
    imho this is way different, the SYSTEMD_WANTS tag is completely ok to use. yes, he may be mounting the drive from the script, but imho he is not "exploiting" anything here. I personally don't see a much more elegant way to do this.
    these automount udev rules were however crappy and hackish. They were created by people who are like "but udisks is bloat!!1!" and whoever wrote them didn't really seem to know what he was doing because, for example, unmounting a device after it was unplugged from the system is completely non-sense.

  • Pkgman - a bash script for local package and PKGBUILD management

    hi all,
    here is a script which manages a local repository and lets you edit
    PKGBUILDs and other related files, automatically generates checksums,
    build packages, add them to your local repo and so on.
    it also has AUR support for submitting tarballs, leaving comments, etc.
    get it from here:
    http://sourceforge.net/projects/pkgman/
    and AUR package:
    http://aur.archlinux.org/packages.php?ID=17100
    you need abs, curl and pacman and optionally namcap and desktop-file-utils.
    RTFM online:
    http://sourceforge.net/apps/mediawiki/p … n_man_page
    first of all copy the pkgman.conf and AUR.conf files from /usr/share/pkgman to ~/.config/pkgman/  or ${XDG_CONFIG_HOME}/pkgman - if ${XDG_CONFIG_HOME} is set,
    edit these two files and then run
    pkgman --runmefirst
    pkgman doesn´t install anything. if you want it just builds the package and moves it to your local repository. install it then with pacman.
    it also has no dependency handling. there are many other tools which provide this.
    the main intention was to keep track of package versions, different PKGBUILD versions and own AUR submitted tarballs; also to keep a clean local repository and clean build directories.
    pkgman is stable now. i´m using it for months without any issues.
    however, if there are problems or feedback please post them here.
    vlad
    changelog:
    version 2.4:
           *pkgman now respects the PKGDEST and SRCDEST variables from makepkg.conf. (though it still moves the src.tar.gz and .pkg.tar.gz to package backup directory).
    version 2.5:
           *pkgman uses PKGDEST if SRCDEST not set in makepkg.conf.
    version 2.6 -> r26:
           *changed version system: version 2.6 is now r26!
           *minor changes: > pkgman uses now the $SHELL variable.
                                    > new and more comprehensible manpage description (thanks to bender02)
    version r27:
           *changed SRCDEST since it's only a cache dir. all files (pkg.tar.gz and src.tar.gz) go to PKGDEST.
    version r28:
           *added new variable ShellCommand to pkgman.conf. Default is $SHELL.
           *One might use an external application (like screen or xterm) to switch to build directory and edit files simultaneously.
    version r30:
           *minor changes. nothing crucial
    r32: *OverwriteExistingPackage isn't used anymore. one can delete it from ~/.config/pkgman/pkgman.conf.
           *minor changes
    version r33:
           *"-l|--list" also shows installed package version and available ABS/AUR PKGBUILD version for given package.
           *"-a|--abs" can now also be used with other options (like "-e")
    r39: * when backing up src.tarballs it asks whether to backup the source file or not
           * more detailed "--list" option - also shows if package is installed or not and available ABS/AUR version
           * added prompt to clean up directory after makepkg
           * when checking pkg.tar.gz also possibility to check for conflicts with files of already installed packages
           * use $PAGER instead of less
           * --help directly shows the manpage
           * --shorthelp shows a brief usage overview
           * added a custom prompt, but only when using bash (is somehow experimental - works fine here for me)
           * minor internal changes
           * pkgman also reads ~/.aurvote file for getting aur name and password. if one already uses aurvote then there is no need for the
             ~/.config/pkgman/AUR.conf file.
    r40: * new manual page & rewrite of usage function
           * both option "--flush" and "--flushall" were omitted in favor of the more versatile "--cleanup" option
           * pkgman <packagename> checks now if <packagename> is owned by user
           * backup option after each editing
           * added license
           * minor internal changes
    r41: * just small bug fixes, nothing crucial.
    r42: * more bugs fixed.
    r45: * new options added:
              >   --listversions: list local and available versions of installed packages from LocalPackages directory
              >  --getownpackages: synchronize local own packages with AUR
           * added new variable in pkgman.conf:
              > ListOutputInPager: output of, for example, "--list" or "--own" is piped into $PAGER
           * added a new optional dependency "desktop-file-utils" for validating desktop entry files
           * also supports now auto-generation of sha sums not only md5
           * internal fixes due to AUR interface changes:
              > use of json interface
              > correct parsing of package category
           * added 2 proto files (located under /usr/share/pacman):
              >  proto.desktop: a template for *.desktop files
              > PKGBUILD-lib32.proto: a template for lib32 packages for x86_64
           * some code changes and fixes
    r46: * added new option to pkgman.conf (AutoGenerateSums).
             > if AutoGenerateSums=no then pkgman asks whether to generate checksums or not.
             > if set to yes it behaves like in former versions.
    r52: * "--getownpackages" with more than 100 packages works again
           * added new option "--cachecopy":
              For each package in CacheCopyList (new variable in pkgman.conf) get existing package from pacman's cache directory - if
              CopyPkgFromCache (new variable in pkgman.conf) is set to yes - and/or create a source tarball of PKGBUILD and related files from ABS -
              if CopySrcFromABS (new variable in pkgman.conf) is set to yes - and copy them to package backup directory.
           * added new variables to pkgman.conf:
               > "CacheCopyList=file" - batch backup file, one package per line - default location is "$HOME/.config/pkgman/package.list".
               > "CopySrcFromABS=[yes|no]"
               > "CopyPkgFromCache=[yes|no]"
           * some bugfixes
           * docs completed
           * CacheCopyList should look like
    package1
    package2
    #this is a comment
    ! this too
    package3
    !package4
    r54: * renamed "--listversions" option to "--diffversions". makes more sense!
              from the man page:
                  pkgman --diffversions
                  Show differing ABS/AUR versions of installed packages from LocalPackages.
    r55: * minor changes.
    r57: * testing release
           * added a new option "--rollback":
               "pkgman <packagename> --rollback" - checks  http://arm.kh.nu for available package versions,
                                                          lets you choose one, fetches the package and
                                                          moves it to the <packagename> backup directory (if "--repoadd" is used).
    r59: * stable release
           * new option "--rollback" (see r57):
                   it checks http://arm.kh.nu (Arch Rollback Machine) for available package versions,
                   downloads chosen file and moves it to local repository (if "-r|--repoadd"  is used).
            * posting files/comments/etc to AUR should work now again.
    r65: *stable release
           * new option "-M,--meta" to create metapackages and add them and their dependencies to local repository.
              it searches for deps inside the backup directories, pacman's cache and if the packages are not available, it tries to fetch the missing
              dependencies from the Arch Rollback Machine site (http://arm.kh.nu).
    r66: * minor fixes
    r68: * some bugfixes
           * "--repoadd" and "--Reporemove" now accurately removes old packages from LocalRepository
    r69: * small bugfixes when listing packages with similar names
           * curl retries now 5 times if connection is not established
    r75: * "--cachecopy" does not try to dl sourcefiles when backing up ABS PKGBUILDs
           * some work on package splitting
           * further internal changes
    r76: * minor mistakes with "ln" purged
    r79: * mostly small changes
           * "--cleanup" now also removes uninstalled packages from LocalRepository
    r81 & r80: * added AUR v1.6.0 support (use more json)
                    * small ARM changes ("--rollback")
    r85:
          * pkgman supports pkg.tar.xz packages
          * some code rewrite, bugs purged (hopefully)
    r113:
          * pkgman now supports building split packages through makepkg.
             If you already use pkgman you need to rerun "pkgman --runmefirst" after updating.
          * new  "-t,--template" option ("pkgman <packagename> --template <alt. packagename> [--pkgbuildversion <version>] [options]").
             Useful to create a new PKGBUILD and use an existing one as a template.
          * new option: "--conf /path/to/alternate/conf/file" - Specify another configuration file.
          * pkgman now uses ${XDG_CONFIG_HOME}/pkgman or $HOME/.config/pkgman - if first not set - as the default location for its conf files.
    r116:
          * check inet conection when submitting src tarballs to AUR
          * some bugs
          * updated manpage on sf
    For further details please read the manual page.
    Last edited by DonVla (2010-04-28 11:56:59)

    I'm having some troubles with it (perhaps missing dependencies, and forgotten hardcoded dirs?):
    jan@aconcagua 8:20PM ~ % pkgman --runmefirst
    /usr/bin/pkgman: line 77: /home/jan/apps/skripte/archscripts/pkgman/share/pkgman/color.bash: No such file or directory
    /usr/bin/pkgman: line 1293: initcolor: command not found
    /usr/bin/pkgman: line 312: highlight: command not found
    /usr/bin/pkgman: line 312: error: command not found
    /usr/bin/pkgman: line 313: highlight: command not found
    /usr/bin/pkgman: line 313: error: command not found
    /usr/bin/pkgman: line 314: highlight: command not found
    /usr/bin/pkgman: line 314: error: command not found
    /usr/bin/pkgman: line 315: highlight: command not found
    /usr/bin/pkgman: line 315: error: command not found
    /usr/bin/pkgman: line 317: error: command not found
    /usr/bin/pkgman: line 318: error: command not found
    /usr/bin/pkgman: line 321: highlight: command not found
    /usr/bin/pkgman: line 321: msg: command not found
    /usr/bin/pkgman: line 329: list: command not found
    /usr/bin/pkgman: line 332: list: command not found
    /usr/bin/pkgman: line 332: list: command not found
    touch: cannot touch `/bin/.pkgman.registered': Permission denied
    /usr/bin/pkgman: line 332: list: command not found
    /usr/bin/pkgman: line 332: list: command not found
    /usr/bin/pkgman: line 332: list: command not found
    /usr/bin/pkgman: line 332: list: command not found
    /usr/bin/pkgman: line 332: list: command not found
    /usr/bin/pkgman: line 337: msg: command not found
    curl: option --output: requires parameter
    curl: try 'curl --help' or 'curl --manual' for more information
    ^C/usr/bin/pkgman: line 209: cleanoutput: command not found
    /usr/bin/pkgman: line 209: cleanoutput: command not found
    (I terminated with ctrl-c).
    EDIT: errors resolved by correcting the path $HOME/apps/skripte/archscripts/pkgman/share/pkgman to /usr/share/pkgman in the pkgman itself.
    Last edited by bender02 (2008-05-23 01:28:58)

  • Any 64 bit driver for Apple USB MA034 Modem Yet?

    Uggghh.....Apple!   Ugggghhhh Me!
    So after being charged for months to use efax, I put a telephone call into my ISP to find that my office line also can handle faxing.  This is great, all I need is a fax machine!  A quick (really quick) google and i read that we could use an Apple USB MA034 Dial Up Modem to send and receive faxes.  Phenomanal!  This is why i love my Macs, just like the old WinFax.  I scour ebay, find one, and paid $12 for a nice one, shipped.
    I further look into how this is going to make my life easier, only to find that I am now screwed, as there isn't a 64 bit driver from Apple to support the modem.  I did see people have talked to Apple and that their could be a driver out there, or one of our fine 3rd party friends may have wrote one?  Id really like to use this thing instead of it being a 12$ paper weight. 
    Anybody find anything out there?  I was really excited about this.  Thanks in advance.

    I'm looking for the same basic thing....
    Does anyone use a Apple Cinema 23" Display with Vista 64 bit? I'm wondering what video card you use on your PC that supports the 23" Apple display.
    I have a DVIator which worked great with XP, but now that my PC has vista, after the vista boot screen starts to appear, I get a black screen.
    Thanks

  • Can't get conky-cli and bash scripts to both display in dwm statusbar!

    I'm trying to configure my dwm status bar to display some simple information using conky-cli and bash scripts. At first I tried just letting conky run the bash scripts (for network and volume state), but this increased my cpu usage by about 5%, which is significant considering I normally have 1-3% usage when idle. Also, I wanted to keep conky because it makes the display of certain information easy, such as cpu & RAM usage.
    The problem is I'm having trouble getting both to display side by side. Here are the relevant parts of my .xinitrc:
    network(){
    iwconfig wlan0 2>&1 | grep -q no\ wireless\ extensions\. && {
    echo wired
    exit 0
    essid=`iwconfig wlan0 | awk -F '"' '/ESSID/ {print $2}'`
    stngth=`iwconfig wlan0 | awk -F '=' '/Quality/ {print $2}' | cut -d '/' -f 1`
    bars=`expr $stngth / 10`
    case $bars in
    0) bar='[-------]' ;;
    1) bar='[#------]' ;;
    2) bar='[##-----]' ;;
    3) bar='[###----]' ;;
    4) bar='[####---]' ;;
    5) bar='[#####--]' ;;
    6) bar='[######-]' ;;
    7) bar='[#######]' ;;
    *) bar='[--!!!--]' ;;
    esac
    echo $essid$bar
    exit 0
    volume(){
    vol=$(amixer get Master | awk -F'[]%[]' '/%/ {if ($7 == "off") { print "MM" } else { print $2 }}' | head -n 1)
    echo Vol: $vol%
    exit 0
    conky | while true; read line; do xsetroot -name "`$line` `volume` `network` `date '+%a %m-%d-%Y %I:%M%p'`"; done &
    exec dwm
    (let me know if it would help to post any other files)
    For some reason when I run this I only get the network/volume scripts and date running, updating every second (I think). The conky line just doesn't show up. I don't know what could be wrong, since I didn't see any error messages.
    An even better solution would be to just have shell scripts to display CPU and MEM usage. I have a dual-core cpu, cpu0 and cpu1. I'd like to see both percentages if possible, or at least a percentage that is an accurate average of the two or something. In conky-cli I have something that shows:
    cpu0/1: xx% xx%
    Also, seeing RAM usage would help a lot. In conky it shows:
    mem: xx% (xxxMB)
    These are the ways I would like to have bash scripts show them, if possible, but I have zero skill in bash programming. I made this an option in case it's easier/cleaner/less resource hungry than a conky solution. Personally, if they're about the same in these aspects, I would prefer something with conky and the shell scripts because conky is so extensible, yet it's only flaw is executing scripts with minimal resource usage.
    Help?

    Thanks. I was thinking of using load average to save a few characters, but I didn't quite understand the numbers. I'll try that once I get to my Linux box, but could you please explain or post a link to something that explains load average (what's low, high, normal, etc.)?
    EDIT: I found a website that explains loadavg. I now have my dwm status bar displaying it perfectly (yay!). Now I just need to add a few more things like battery status, etc. and I might be done. I'll probably post here if I have more questions, though.
    Thanks for your help!
    Last edited by Allamgir (2009-07-18 14:41:11)

  • /etc/rc.d/network: bash script: how to find out, if there was an error

    hello!
    i want to write a bash script for my wireless lan. for this i need the information, if the network daemon has connected successfully or failed.
    but there is a big problem: starting network success' every time, whether there was an error or not:
    $ /etc/rc.d/network start
    :: Starting network profile: 00wlan_home [BUSY]
    Error for wireless request "Set Mode" (8B06) :
    SET failed on device wlan0 ; No such device.
    [FAIL]
    :: Starting Network [DONE]
    $ ls /var/run/daemons/
    ... network ...
    can someone help me please? how can i realize  that "::Starting Network ..." also fails and the script returns an exit status 1?
    thanks for your help, maybe we can improve the script. but i'm not a geek in bash!
    mfg iggy

    iggy wrote:
    hello!
    i want to write a bash script for my wireless lan. for this i need the information, if the network daemon has connected successfully or failed.
    but there is a big problem: starting network success' every time, whether there was an error or not:
    $ /etc/rc.d/network start
    :: Starting network profile: 00wlan_home [BUSY]
    Error for wireless request "Set Mode" (8B06) :
    SET failed on device wlan0 ; No such device.
    [FAIL]
    :: Starting Network [DONE]
    $ ls /var/run/daemons/
    ... network ...
    can someone help me please? how can i realize  that "::Starting Network ..." also fails and the script returns an exit status 1?
    thanks for your help, maybe we can improve the script. but i'm not a geek in bash!
    mfg iggy
    try using netcfg to start the wireless profile, that should keep you happy until the new network scripts are unleashed... which won't have this problem.
    James

  • Mpc in bash script

    hi,
    I am trying to write a little bash script for adding all songs with the same artist as the currently playing song. Here is what I already have:
    artist=`mpc -f %artist% | head -n 1`
    search=`mpc search artist "$artist" | sed 's|mp3|mp3"|g' | sed 's|ganze|"ganze|g'`
    echo $search | mpc add
    the sed commands are for enclosing all paths in the list by "
    the point is that the last command doesn't work and I don't know why! if I type
    echo $search
    and copy the the output to the end of mpc add, mpd adds the songs to it's playlist. so my problem here is that mpc doesn't "eat" the content of the search-variable in the pipe. what am I doing wrong????
    thx in advance

    brisbin33 wrote:
    kittykatt wrote:Have you thought of surrounding the $search variable in double quotes in the last line? If there are spaces involved in that variable, then you'll most likely need them.
    As far as I know, echo doesn't care about quotes unless you're trying to preserve whitespace at the beginning or end of the line.
    # these are equivalent
    var='my awesome variable'
    echo $var
    echo "$var"
    # but these you need to be careful
    var=' my awesome variable with whitespace '
    echo $var
    echo "$var"
    Touche. It's been a long day for me, unfortunately. Starting to make slip-ups like that.

  • A script for setting a random wallpaper

    I've cooked up this small bash script for changing the wallpaper to a random one from a specified directory (it is recursive)
    The script tries to be smart in determining whether the wallpaper should be scaled, centered or tiled.
    Just configure it and try it out.
    Anyway, here goes:
    #!/bin/bash
    # Random wallpaper setter, by moljac024
    # Configuration
    # Wallpaper directory
    wpDir="$HOME/Wallpapers"
    # Wallpaper list path
    wpList=$HOME/.wallpaper-list
    # Folders to be skipped, you can put as many as you like
    #wpSkip=("Dir1/" "Dir2/")
    # Scale images that have a lower resolution than that of the screen (yes or no)
    scaleLowerRes="yes"
    #scaleLowerRes="no"
    # Screen resolution
    resWidth=1280
    resHeight=800
    # Command for tiling the wallpaper
    cmdTile="feh --bg-tile"
    #cmdTile="nitrogen --set-tiled --save"OA
    #cmdTile="xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-style -s 2 && xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s"
    #cmdTile="gconftool-2 -t str --set /desktop/gnome/background/picture_options "wallpaper" -t str --set /desktop/gnome/background/picture_filename"
    # Command for scaling the wallpaper
    cmdScale="feh --bg-scale"
    #cmdScale="nitrogen --set-scaled --save"
    #cmdScale="xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-style -s 3 && xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s"
    #cmdScale="gconftool-2 -t str --set /desktop/gnome/background/picture_options "zoom" -t str --set /desktop/gnome/background/picture_filename"
    # Command for centering the wallpaper
    cmdCenter="feh --bg-center"
    #cmdCenter="nitrogen --set-centered --save"
    #cmdCenter="xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-style -s 1 && xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s"
    #cmdCenter="gconftool-2 -t str --set /desktop/gnome/background/picture_options "centered" -t str --set /desktop/gnome/background/picture_filename"
    # End of configuration
    setTiled ()
    `$cmdTile "$1"`
    if [ "$?" = "0" ]; then
    echo "Wallpaper tiled."
    else
    echo "Wallpaper not set!"
    exit 1
    fi
    setScaled ()
    `$cmdScale "$1"`
    if [ "$?" = "0" ]; then
    echo "Wallpaper scaled."
    else
    echo "Wallpaper not set!"
    exit 1
    fi
    setCentered ()
    `$cmdCenter "$1"`
    if [ "$?" = "0" ]; then
    echo "Wallpaper centered."
    else
    echo "Wallpaper not set!"
    exit 1
    fi
    createList ()
    # Go to the wallpaper directory
    cd "$wpDir"
    # Load the list of pictures to a variable
    wpDirList=`(find . -regex ".*\([jJ][pP][gG]\|[jJ][pP][eE][gG]\|[gG][iI][fF]\|[pP][nN][gG]\|[bB][mM][pP]\)$" -type f)`
    # Save the list to disk
    if [[ ( -w "$wpList" ) ]]; then
    echo -n "$wpDirList" > "$wpList"
    # Filter out unwanted folders
    if [[ "$dontSkip" == "false" ]]; then
    for dir in "${wpSkip[@]}"
    do
    grep -Ev "$dir" "$wpList" > ~/.wallpapers-tmpr; mv ~/.wallpapers-tmpr "$wpList"
    done
    fi
    # Output result
    echo "Wallpaper list saved."
    else
    echo "Can't write wallpaper list, aborting!"
    exit 1
    fi
    getImage ()
    # Count number of pictures in the wallpaper list by counting number of lines.
    # Check if the wallpaper list exists, is not empty and we have read persmission on it
    if [[ ( -s "$wpList" && -f "$wpList" ) && -r "$wpList" ]]
    then
    wpListNumber=$(wc -l < "$wpList")
    else
    echo "Can't read wallpaper list, aborting!";
    exit 1
    fi
    # Counter for bad entries in wallpaper list
    badMax=100
    while true; do
    # Get a seed for the random number generator from /dev/urandom
    SEED=$(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')
    RANDOM=$SEED
    # Find a random line number in the wallpaper list
    # Random number from 1..n.
    #r=$((RANDOM % $wpListNumber + 1))
    r=$(echo $RANDOM%"$wpListNumber"+1 | bc)
    # Print what the line number is
    # Print the r'th line.
    imgPath=`sed -n "$r{p;q;}" "$wpList"`
    # #./ crops that substring but it doesn't matter if it left there
    wpPath="${wpDir}${imgPath#./}"
    # Check if the chosen file exists
    if [ -f "$wpPath" ]; then
    break
    else
    echo -e ""$wpPath": doesn't exist!\n"
    badMax=$(( $badMax - 1 ))
    if [ "$badMax" == "0" ]; then
    echo "Too many non-valid entries found in wallpaper list, aborting!"
    exit 1
    else echo "Choosing new image..."
    fi
    continue
    fi
    done
    # Calculate size and aspect for chosen image and print out information
    imgHeight=$(identify -format "%h" "$wpPath")
    imgWidth=$(identify -format "%w" "$wpPath")
    imgAspect=$(echo "scale=1; "$imgWidth"/"$imgHeight"" | bc)
    echo -e "Image: "$wpPath"\n"
    echo -e "Resolution: "$imgWidth"x"$imgHeight""
    echo -e "Aspect: "$imgAspect":1\n"
    setWallpaper ()
    # Calculate resolution aspect ratio
    resAspect=$(echo "scale=1; "$resWidth"/"$resHeight"" | bc)
    # If the image is smaller than the resolution and is not a tile then scale it, otherwise look at aspect
    if [[ ("$scaleLowerRes" == "yes") && ( "$imgAspect" != "1.0" && ("$imgWidth" -lt "$resWidth" || "$imgHeight" -lt "$resHeight") ) ]]
    then
    setScaled "$wpPath"
    else
    case $imgAspect in
    1.0)
    setTiled "$wpPath"
    1.5 | 1.6 | 1.7 | 1.8)
    if [[ "$resAspect" < "1.5" ]]; then
    setCentered "$wpPath"
    else
    setScaled "$wpPath"
    fi
    if [[ "$resAspect" < "1.5" ]]; then
    setScaled "$wpPath"
    else
    setCentered "$wpPath"
    fi
    esac
    fi
    checkConfig ()
    # Initial errors
    errorsPresent="no"
    dontSkip="false"
    # Check if all variables are set
    if [[ !( ( -n "$wpDir" ) && ( -n "$wpList" ) && ( -n "$resWidth" ) && ( -n "$resHeight" ) && ( -n "$scaleLowerRes" ) && ( -n "$cmdTile" ) && ( -n "$cmdScale" ) && ( -n "$cmdCenter" ) ) ]]
    then
    echo -e "\nOne or more options not set, aborting!"
    exit 1
    fi
    # Check if there is a trailing backslash in the wallpaper directory
    spDir=`echo -n "$wpDir" | tail -c -1`
    if [[ !( "$spDir" == "/" ) ]]
    then
    wpDir=""$wpDir"/"
    fi
    # Check if there is read permission on wallpaper directory and if it is a directory
    if [[ !( ( -r "$wpDir" ) && ( -d "$wpDir" ) ) ]]
    then
    echo "Can't read wallpaper directory!"
    errorsPresent="yes"
    fi
    # Check if the specified wallpaper list is a regular file and not a directory
    touch "$wpList" &> /dev/null
    if [[ ( -d "$wpList" ) ]]
    then
    echo "Specified wallpaper list is a directory, not a file!"
    errorsPresent="yes"
    fi
    # Check if variables are set correctly
    if [[ !( "$scaleLowerRes" == "yes" || "$scaleLowerRes" == "no" ) ]]
    then
    echo "Specified option for scaling the wallpaper is not valid!"
    errorsPresent="yes"
    fi
    if $(echo ""$resWidth"" | grep [^0-9] &>/dev/null)
    then
    echo "Specified resolution width is not a number!"
    errorsPresent="yes"
    fi
    if $(echo ""$resHeight"" | grep [^0-9] &>/dev/null)
    then
    echo "Specified resolution height is not a number!"
    errorsPresent="yes"
    fi
    # Check if any of the tests failed
    if [[ "$errorsPresent" == "yes" ]]
    then
    echo -e "\nOne or more errors found, aborting!"
    exit 1
    fi
    ignoreWPSkip()
    dontSkip="true"
    printUsage ()
    echo -e "Invalid command line argument(s)!\nUsage:\n"
    echo -e "`basename "$0"` [options]\n"
    echo -e "Options:\n"
    echo -e "-s | --set \tSet a wallpaper without updating the list"
    echo -e "-u | --update \tUpdate the list without setting a wallpaper"
    echo -e "-ua | --update-all\tUpdate the list without setting a wallpaper, but don't skip any folders"
    echo -e "-su | --set-update\tUpdate the list and set a wallpaper"
    exit 1
    if [ "$#" == "1" ]; then
    case "$1" in
    "-s" | "--set")
    checkConfig
    getImage
    setWallpaper
    exit 0
    "-u" | "--update")
    checkConfig
    createList
    exit 0
    "-ua" | "--update-all")
    checkConfig
    ignoreWPSkip
    createList
    exit 0
    "-su" | "--set-update")
    checkConfig
    createList
    getImage
    setWallpaper
    exit 0
    printUsage
    exit 1
    esac
    else
    printUsage
    exit 1
    fi
    Last edited by moljac024 (2009-09-14 21:02:13)

    I did something similar a couple of months ago, but instead of attempting to be clever and guessing what the background image is supposed to be, I just write it in the filename. Since some pictures just end up being too bright (or whatever) when used as a background to a urxvt terminal, I added some extra parameters for setting gamma, brightness, tint and the direction the image should be rendered. It relies on hsetroot for actually rendering the picture.
    #!/usr/bin/python
    # set-background
    import sys, os, string, re
    patterns = [ (re.compile("t-([a-f\d]+)"), lambda x: "-tint \#" + x)
    , (re.compile("b-([\d]+)"), lambda x: "-brightness -0." + x)
    , (re.compile("g-([\d]+)"), lambda x: "-gamma "+ x)
    , (re.compile("f-(v|h|d)"), lambda x: "-flip" + x)
    def buildCommand(file):
    output = ["hsetroot"]
    output.append("-" + (string.split(file,".")[-2]))
    output.append(file)
    for token in string.split(file,".")[1:-2]:
    for (pat,f) in patterns:
    if pat.match(token):
    output.append( f(pat.findall(token)[0]))
    return string.join(output)
    print buildCommand(img)
    os.system(buildCommand(img))
    # vim:set et:
    So for instance, an image with the name background.t-704214.f-v.full.jpg would be rendered as a stretched image, flipped vertically with a sepia tint. The files are required to be in the following format NAME.(MODIFIER.)*TYPE.SUFFIX, where the the order and number of modifiers are unimportant. The gamma values are somewhat unintuitive, but I guess you'll just have to play around with it to get it right.
    And to randomize the whole thing, I just used the following script in my .xinitrc to randomly pick a image from a folder.
    #!/bin/bash
    bg_folder="$HOME/.backgrounds";
    pics=($(ls $bg_folder))
    let "n = $RANDOM % ${#pics[@]}"
    (cd $bg_folder; set-background ${pics[$n]})

  • USB ADSL Modem Driver for Huawei MT841 for Solaris Express

    Hello Everyone
    After initial hiccups of installing Solaris Express in a multiboot system and partition mania,i finally installed Solaris Express on my system.First i installed Developer Edition and upgraded it to Express thinking that Developer Edition doesnt have networking capabilities.
    All said and done now i'm unable to access the internet.I'm using Broadband USB ADSL Modem from Huawei,type MT841 with four ethernet ports and one USB port.I dont have ethernet card so i use USB port to connect.
    The thing is the modem cd doesnt have a driver for Solaris,but for linux it does.
    Where can i find the driver for ADSL modem and how to install it,if i find it?
    Is there any alternate way?Expecting a reply(because my last post about multiboot didnt)
    Thanks in advance
    C.S.Shreeram

    Problem Solved!
    Un-installing all USB modem device drivers, disconnecting all USB devices and removing all USB host controllers and hubs from the Vista device manager and then rebooting the notebook MADE NO DIFFERENCE.
    However when I received the new Thomson SpeedTouch 330 USB ADSL modem drivers on CD-ROM from the manufacturer the modem installed immediately.
    I can only assume that there is a problem with the download of Release 4.1 of the Windows Vista driver for the SpeedTouch 330 from this web-page:
    http://www.thomson-broadband.co.uk/codepages/content3.asp?c=7&ProductID=471
    ... as the drivers on the CD-ROM from Thomson work - but their web download of the driver for the SpeedTouch does not.
    The problem was with the driver for Windows Vista - the laptop and modem now work correctly - as they should have done at the first installation attempt!
    Thanks for your help.

  • [SOLVED] automatic usb-backup with udev-rules + script

    I would like to have my usb-harddrive automatically start a backup as soon as it is plugged in.  And finally a bell is supposed to ring.
    I've created an udev-rule and a backup-script as shown below.
    However, instead of creating /dev/backup-drive first something strange is happening:
    The bell rings 3 times, followed by the backup, followed by a 4th ring.
    What's going on?
    Here's may udev-rule:
    ## /etc/udev/rules.d/95-backup.rules
    SUBSYSTEMS=="usb", ATTRS {serial}=="100", SYMLINK=="backup-drive", RUN+="/usr/local/bin/backup-thumb.sh"
    fstab:
    /dev/backup-drive    /media/backup   ext3     rw,user    0 0
    and my script:
    #!/bin/bash
    sleep 10
    rsync -vrtolgh --exclude '/.VirtualBox/' --delete /home/myhome /media/backup-drive
    aplay /usr/share/sounds/phone.wav
    Last edited by mehldutt (2007-07-03 20:28:27)

    The syntax of your udev rule is all wrong - for example after SYMLINK you should use "+=" or ":=". "==" is for comparing to some value.
    I think in rsync command line you want -H not -h (help) option. Also -v (verbose) is useless since you'll never see the output.
    Another thing which will prevent running rsync properly is /media/backup-drive while you use /media/backup in fstab.
    I suggest that you first try running rsync command from the command line "manually" and try if it works at all. After you'll make it work try the below suggestions.
    Another problem: what makes the backup drive mounted under /media/backup directory when you plug it into usb slot ? Are you doing it somehow "manually" in the 10 second period after plugging ? Do you use automounter of some kind ?
    If you intend to use ext3 as the backup drive filesystem you should also add sync command after rsync to make sure no data stays in RAM cache.
    I think you need to read udev manpage first.
    I can also advice you to read my udev rules for automounting usb devices (it's for any type of filesystem and any number of partitions):
    KERNEL=="sd[b-z]", NAME:="%k", SYMLINK+="usbhd-%k", GROUP:="users", OPTIONS="last_rule"
    ACTION=="add", KERNEL=="sd[b-z][0-9]", SYMLINK+="usbhd-%k", GROUP:="users", NAME:="%k"
    ACTION=="add", KERNEL=="sd[b-z][0-9]", RUN+="/bin/mkdir -p /media/usbhd-%k"
    ACTION=="add", KERNEL=="sd[b-z][0-9]", RUN+="/bin/ln -s /media/usbhd-%k /mnt/usbhd-%k"
    ACTION=="add", KERNEL=="sd[b-z][0-9]", PROGRAM=="/lib/udev/vol_id -t %N", RESULT=="vfat", RUN+="/bin/mount -t vfat -o rw,noauto,flush,dirsync,noexec,nodev,noatime,dmask=000,fmask=111 /dev/%k /media/
    usbhd-%k", OPTIONS="last_rule"
    ACTION=="add", KERNEL=="sd[b-z][0-9]", RUN+="/bin/mount -t auto -o rw,noauto,async,dirsync,noexec,nodev,noatime /dev/%k /media/usbhd-%k", OPTIONS="last_rule"
    ACTION=="remove", KERNEL=="sd[b-z][0-9]", RUN+="/bin/rm -f /mnt/usbhd-%k"
    ACTION=="remove", KERNEL=="sd[b-z][0-9]", RUN+="/bin/umount -l /media/usbhd-%k"
    ACTION=="remove", KERNEL=="sd[b-z][0-9]", RUN+="/bin/rmdir /media/usbhd-%k", OPTIONS="last_rule"
    I think it could be simplified and modified for your backup device like this:
    SUBSYSTEMS=="usb", ATTRS(idVendor)=="XXXX", ATTRS(idProduct)=="YYYY", KERNEL=="sd[a-z]", NAME:="%k", SYMLINK:="backupdevice", OPTIONS="last_rule"
    SUBSYSTEMS=="usb", ATTRS(idVendor)=="XXXX", ATTRS(idProduct)=="YYYY", ACTION=="add", KERNEL=="sd[a-z]1", SYMLINK:="backuppartition", GROUP:="users", NAME:="%k"
    SUBSYSTEMS=="usb", ATTRS(idVendor)=="XXXX", ATTRS(idProduct)=="YYYY", ACTION=="add", KERNEL=="sd[a-z]1", RUN+="/bin/mount -t auto -o rw,noauto,async,dirsync,noexec,nodev,noatime /dev/%k /media/backup-drive"
    SUBSYSTEMS=="usb", ATTRS(idVendor)=="XXXX", ATTRS(idProduct)=="YYYY", ACTION=="add", KERNEL=="sd[a-z]1", RUN+="/usr/local/bin/backup-thumb.sh", OPTIONS="last_rule"
    SUBSYSTEMS=="usb", ATTRS(idVendor)=="XXXX", ATTRS(idProduct)=="YYYY", ACTION=="remove", KERNEL=="sd[a-z]1", RUN+="/bin/umount -l /media/backup-drive", OPTIONS="last_rule"
    assuming that you have a single partition backup drive formatted as ext3 (or at least it's the first partition).
    Also another assumption is that idVendor and idProduct are unique to your backup drive. If not you should add some extra ATTRS parameters that will ensure this combination is unique.
    The directory /media/backup-drive must already exist (remove your fstab line - it's not needed in this case because mount command is run directly from the udev rule).
    Replace all XXXX and YYYY with the values from lsusb for your backup device - plug it in, run lsusb and copy values which look like XXXX:YYYY near to the name of your backup device.
    Anyway, you can play with different options and try to modify it yourself. The automounting rules work for me very well for some time (including flush option). The backup rules you need to test yourself :-)
    Last edited by lanrat (2007-05-05 17:20:51)

  • Bash script to mount/umount usb ?

    this thread https://bbs.archlinux.org/viewtopic.php?id=185712 gave me an idea and teach me.
    I created a script to mount/umount usb. Save it in user's home dir, do
    chmod
    and click on it as a toggle button to mount/umount usb.
    It only work for one usb plugged in. Please suggest me to get it work for two or more.
    #! /bin/bash
    # mr = mounted result
    # ur = umounted result
    # er = empty result
    # cm = check mountpoint
    # cup = check usb is plugged in
    # usb = usb device (Example... /dev/sdb1)
    cm=$(mountpoint /home/username/tmp)
    cup=$(lsblk | grep "sd[b-z]1")
    usb=$(ls /dev/sd[b-z]1)
    er=""
    ur="/home/username/tmp is not a mountpoint"
    mr="/home/username/tmp is a mountpoint"
    if [ "$cm" == "$ur" ] && [ "$cup" != "$er" ]; then
    echo "password" | sudo -S mount -o uid=username,gid=users $usb /home/username/tmp
    elif [ "$cm" == "$mr" ] && [ "$cup" != "$er" ]; then
    echo "password" | sudo -S umount /home/username/tmp
    else
    exit
    fi

    There are a number of issues with your script; the reason you can't mount more than one device is that if "${usb[@]}" is populated by more than one drive, you need to iterate over the array to mount them.
    Other issues that you should consider are:
    your variable names are brief to the point of unintelligble: it is very hard to follow what is going on with "$mr", "$ur", "$cr" etc
    don't parse the output of `ls`
    don't put messages in variables; `printf` them
    relatedly; check exit status, not strings: `$?`
    if you are using bash; see What is the difference between [ and [[?
    rather than `echo`ing your password (see 3), add the script to `sudoers`
    Hope (some of) that helps.

Maybe you are looking for