Get initial directories in bash script

I have a variable TEST in a bash script
TEST=/ABCService/ZeroComposite/deploy/sca_XYZ.jar
I want to parse this TEST variable to have a new variable COMPOSITE_DIR with value "/ABCService/ZeroComposite". Looks pretty simple but I am on it for about 3 hours now. Exhausted all option with regex, dirname, basename etc. There has to be a simple way to do this.
Thanks

Giving up after only 3 hours already?
How about the following:
var=$(echo $TEST | rev | cut -d'/' -f3- | rev)
echo $var
/ABCService/ZeroComposite
The cut command allows to specify a character delimiter that acts like a field separator. The parameter -f3- would normally extract the string starting at field number 3 and all remaining fields. The trick is to reverse the order of the string so that the cut command will cut from the end to the beginning, instead from the beginning to the end, and then reverse the string again to get the result.

Similar Messages

  • 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)

  • Getting 2 errors in bash script

    /Users/Myname/Desktop/Printer Install 2: line 115: unexpected EOF while looking for matching `"'
    /Users/myname/Desktop/Printer Install 2: line 119: syntax error: unexpected end of file
    logout
    Please help I have no idea what is causing it. If I do a fake example script it works fine.
    #!/bin/bash
    PS3='Please enter your choice: '
    options=("Andover" "Barkhamsted" "Berlin" "Bethany" "Bethlehem" "Bolton" "Bozrah" "Branford" "Bridgeport" "Bristol" "Brookfield" "Brooklyn" "Burlington" "Canaan" "Canton" "Chaplin" "Chester" "Colebrooke" "Cornwall" "Coventry" "Cornwall” Cromwell" "Danbury" "Darien" "Deepriver" "Derby" "Quit")
    select opt in "${options[@]}"
    do
        case $opt in
            "Andover")
    /usr/sbin/lpadmin -p Andover -L Unknown -E -v lpd:/172.16.62.160 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ CPP4005.gz
                echo "installed Andover”
    "Barkhamsted")
    /usr/sbin/lpadmin -p Barkhamsted -L Unknown -E -v lpd:/172.16.62.124 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 4200\ series.gz
    echo "installed Barkhamsted”
                   "Berlin”)
    /usr/sbin/lpadmin -p Berlin -L Unknown -E -v lpd:/172.28.165.249 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 400\ M401dne.gz
                echo “Installed Berlin”
    "Bethany”)
    /usr/sbin/lpadmin -p Bethany -L Unknown -E -v lpd:/172.16.62.17 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3010\ series.gz
                echo “installed Bethany”
    "Bethlehem")
    /usr/sbin/lpadmin -p Bethlehem -L Unknown -E -v lpd:/172.16.62.74 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3005.gz
                echo “Installed Bethlehem”
    "Bolton")
    /usr/sbin/lpadmin -p Bolton -L Unknown -E -v lpd:/172.16.62.64 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3005.gz
                echo “Installed Bolton”
    "Bozrah")
    /usr/sbin/lpadmin -p Bozrah -L Unknown -E -v lpd:/172.16.62.89 -P afp:/al786.law.yale.edu/printers/PPDs/Contents/Resources/Kyocera\ CS\ 520i.PPD
                echo “Installed Bozrah”
    "Branford")
    /usr/sbin/lpadmin -p Branford -L Unknown -E -v lpd:/172.16.62.83 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 2430.gz
                echo “Installed Bradford”
    "Bridgeport")
    /usr/sbin/lpadmin -p Bridgeport -L Unknown -E -v lpd:/172.16.62.250 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3005.gz
                echo “Installed Bridgeport”
    "Bristol")
    /usr/sbin/lpadmin -p Bristol -L Unknown -E -v lpd:/172.28.84.109 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3010\ series.gz
                echo “Installed Bristol”
    "Brookfield")
    /usr/sbin/lpadmin -p Brookfield -L Unknown -E -v lpd:/172.16.62.62 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3010\ series.gz
                echo “Installed Brookfield”
    "Brooklyn”)
    /usr/sbin/lpadmin -p Brooklyn -L Unknown -E -v lpd:/172.16.62.86 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3010\ series.gz
                echo “Installed Brooklyn”
    "Burlington”)
    /usr/sbin/lpadmin -p Burlington -L Unknown -E -v lpd:/172.16.62.44 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3010\ series.gz
    echo “Installed Burlington”
    "Canaan")
    /usr/sbin/lpadmin -p Canaan -L Unknown -E -v lpd:/172.16.62.91 -P /Library/Printers/PPDs/Contents/Resources/HP\ Color\ LaserJet.gz
                echo “Installed Canaan”
    "Canton")
    /usr/sbin/lpadmin -p Canton -L Unknown -E -v lpd:/172.16.62.101 -P /Library/Printers/PPDs/Contents/Resources/HP\ Color\ LaserJet\ 4650.gz
                echo “Installed Canton”
    "Chaplin")
    /usr/sbin/lpadmin -p Chaplin -L Unknown -E -v lpd:/172.28.84.213 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P4010_P4510\ series.gz
                echo “Installed Chaplin”
    "Chester")
    /usr/sbin/lpadmin -p Chester -L Unknown -E -v lpd:/130.132.165.125 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 5Si\ Mopier.gz
                echo “Installed Chester”
    "Colebrooke")
    /usr/sbin/lpadmin -p Colebrooke -L Unknown -E -v lpd:/172.28.165.199 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3010\ series.gz
                echo “Installed Colebrooke”
    "Cornwall”)
    /usr/sbin/lpadmin -p Cornwall -L Unknown -E -v lpd:/172.16.62.20 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 4350.gz
                echo “Installed Cornwall”
    "Coventry")
    /usr/sbin/lpadmin -p Cornwall -L Unknown -E -v lpd:/172.16.62.20 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 4350.gz
                echo “Installed Coventry”
    "Cromwell")
    /usr/sbin/lpadmin -p Cromwell -L 127-Wall-St-RM345 -E -v lpd:/172.16.62.47 -P /Library/Printers/PPDs/Contents/Resources/Ricoh\ Aficio\ MP\ 6002.gz
                echo “Installed Cromwell”
    "Danbury")
    /usr/sbin/lpadmin -p Danbury -L Unknown -E -v lpd:/172.16.62.70 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 5200.gz
                echo “Installed Danbury”
    "Darien")
    /usr/sbin/lpadmin -p Darien -L Unknown -E -v lpd:/172.16.62.63 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 5100\ Series.gz
                echo “Installed Darien”
    "Deepriver")
    /usr/sbin/lpadmin -p Deepriver -L Unknown -E -v lpd:/172.16.62.23 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ 9050.gz
                echo “Installed Deepriver”
    "Derby")
    /usr/sbin/lpadmin -p Derby -L Unknown -E -v lpd:/172.16.62.76 -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\ P3005.gz
                echo “Installed Derby”
    "Quit")
    break
    *) echo "invalid option"
        esac
    done

    1. Can I suggest creating a CSV file, which has a three fields per line, e.g.
    Andover,172.16.62.160,CPP4005.gz
    2. Write a simple loop
    PS3='Please enter your choice: '
    # Get option. Add logic if it is not Quit
        Cty=`grep "${UserInput}" CSVFileName  | awk '{print $1}'`
        Ip=`grep "${UserInput}" CSVFileName  | awk '{print $2}'`
        Fname=`grep "${UserInput}" CSVFileName  | awk '{print $3}'`
        echo "Installing ${Cty}"
        /usr/sbin/lpadmin -p ${Cty} -L Unknown -E -v lpd:/${Ip} -P /Library/Printers/PPDs/Contents/Resources/HP\ Laserjet\${Fname}
        echo "Installed ${Cty}"
    The script remains untouched if you add or remove input lines, instead of having to modify the script to address the Case statements.
    PS: This should be to the OP.

  • [SOLVED] How to get BASH scripts to recognize mounted partition paths?

    I don't understand how to get the bash script in the root partition to find the boot partition--both mounted at /mnt.
    I'm following the instructions on configuring "dm-crypt with LUKS" tutorial. The mkinitcpio command to generate the "initial ram disk environment" is producing an error while the system is booted from the install disk and the volumes it looks for are mounted at /mnt.
    #mkinitcpio -p linux
    ==> Building image from preset: /etc/mkinitcpio.d/linux/preset: 'default'
    -> -k /boot/vmlinuz-linux -c /etc/mkinitcpio.conf -g /boot/initramfs-linux.img
    ==> ERROR: specified kernel image does not exist: `/boot/vmlinuz-linux'
    ==> Building image from preset: /etc/mkinitcpio.d/linux/preset: 'fallback'
    -> -k /boot/vmlinuz-linux -c /etc/mkinitcpio.conf -g /boot/initramfs-linux-fallback.img -S autodetect
    ==> ERROR: specified kernel image does not exist: `/boot/vmlinuz-linux`
    The script located in /mnt/root/etc can't find the "temporary kernel" located at /mnt/boot.
    Last edited by xtian (2013-09-17 22:01:35)

    And read them carefully, there should be no /mnt/root/etc/.
    There should be a /mnt/etc/ and a /mnt/boot and /mnt/root/ which is the root user's home directory, not the root filesystem (and of course /mnt/usr ...) - or if you decide to nest the whole thing deeper you could have /mnt/somename/etc and /mnt/somename/boot ...

  • 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.

  • ???? how to launch bash script in cron ????

    with help from people in this forum, I successfully debugged the syntax in a shell script I wrote (my syntactical faux pas had to do with sending a multi-line mail message from a bash script).
    I can manually launch my script from Terminal's command line, and it works perfectly (well, at least it does exactly what I told it to do:). I try to launch it via cron, and it doesn't appear to ever launch.
    In /var/cron/tabs/root, the pertinent line of text reads:
    00 22 * * * /usr/local/customShellScripts/script.sh
    so it is supposed to launch daily at 10PM.
    Other jobs listed in /var/cron/tabs/root do run, because I get emails to my postfix admin account saying that they do. However, none of those other jobs are shell scripts; they are stuff like:
    24 06 * * 5 /usr/sbin/diskutil verifyVolume /
    The directory listing for /var/cron/tabs/root reads:
    $ ls /var/cron/tabs
    total 4
    drwxr-xr-x 3 root wheel 102 Mar 25 18:53:28 2006 .
    drwxr-xr-x 3 root wheel 102 Mar 20 17:13:47 2005 ..
    -rw-r--r-- 1 root wheel 1040 Mar 31 20:28:10 2006 root
    The directory listing for script.sh reads:
    $ ls /usr/local/customShellScripts/
    total 24
    drwxr-xr-x 6 root wheel 204 Mar 31 18:31:27 2006 .
    drwxr-xr-x 11 root wheel 374 Mar 5 12:26:23 2006 ..
    -rw-r--r-- 1 root wheel 6148 Feb 4 14:13:22 2006 .DS_Store
    -rwxr-xr-x 1 root wheel 8058 Mar 31 20:27:50 2006 script.sh
    for debug, the first two lines of script.sh read:
    #!/bin/sh
    /usr/bin/touch /foo
    but the file /foo never gets created. I tried using just "touch /foo" and that didn't work either.
    Also, since the script has a lot of calls to "echo," "expr," "date," "cut," "awk," etc., if I ever get cron to execute the script past the shebang line, do I have to preface all those calls with their full path? Or can I do something like in the old /etc/crontab file, where they defined a path variable up front
    PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
    and the script will be smart enough to look in those directories for the appropriate executables?
    But, getting back to the first problem, I am obviously overlooking something very basic, which is not surprising since I'm self-taught (and I guess, Apple Unix Discussions forum taught) at this unix thing and shell scripting. So, can anybody bail me out here...again?
    2001 Quicksilver G4   Mac OS X (10.4.5)  

    Hey Reese
    You bailed me out, dude! Apparently, my difficulties stemmed from me trying to directly edit /var/cron/tabs/root with pico. Never seemed to bother the other stuff, but it did this time. I am totally inept with vi, the default editor for crontab -e, which is why I had cheated before, and directly edited the /var/cron/tabs/root, el.al., so I had to find out how to
    export EDITOR='pico'
    in my .bashrc
    After having done that, no problem, except for a latent programming logic bug that has reared its ugly head (my script is doing some date manipulation with today's and yesterday's date, and my script crashed and burned on the month change and with stuff related to single-digit date sequence numbers <10).
    But, hey, I learned how to reset my default editor, so as to make life easier for me when it comes time to dorking with crontab files, and I learned that when the crontab file says "DO NOT EDIT THIS FILE - edit the master and reinstall," it means it!
    Thanx for the troubleshooting hint.

  • Unexpected token `(' in my bash script [Solved]

    I've been working on a bash script, and I'm trying to get it to move all directories that are not named certain names to another directory.
    EDIT: Fixed the thing papajoke pointed out
    #!/bin/bash
    mv ~/Downloads/!(folders|pics|docs|code|archives|vids|sounds)/ ~/Downloads/folders/
    The command from the script does what I want it to do when I run it from a terminal.
    It also works if I run the script as follows:
    source script.sh
    It doesn't work like this:
    bash script.sh
    I'm trying to get it to run when I login, and using the running the command with "source" in my MATE Startup Applications doesn't work.
    I'm new to bash scripting, any help would be much appreciated.  Thanks
    Last edited by physicsshark (2015-04-07 20:09:07)

    Trilby wrote:I've never seen that syntax
    You mean the pipes or the bang?
    $ touch a.gz b.gz c.txt
    $ ls !(*.gz)
    c.txt
    This works as an alias and from the comeliness commandline, but not in a script.
    $ ls -l ~/2
    total 16
    drwxr-xr-x 2 karol users 4096 Apr 7 03:13 a
    drwxr-xr-x 2 karol users 4096 Apr 7 03:07 b
    drwxr-xr-x 2 karol users 4096 Apr 7 03:07 c
    drwxr-xr-x 2 karol users 4096 Apr 7 03:13 d
    $ mv ~/2/!(a|b|c) ~/2/a
    $ ls -l ~/2
    total 12
    drwxr-xr-x 3 karol users 4096 Apr 7 03:14 a
    drwxr-xr-x 2 karol users 4096 Apr 7 03:07 b
    drwxr-xr-x 2 karol users 4096 Apr 7 03:07 c
    $ ls -l ~/2/a
    total 4
    drwxr-xr-x 2 karol users 4096 Apr 7 03:13 d
    Last edited by karol (2015-04-07 01:20:14)

  • [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.

  • Conky with a bash script

    I am trying to change the color of my CPU temp text in conky to green, yellow or red based on the CPU temp.  I am getting this in my conky:
    Temperature:  color green33
    Here is my conky line:
    ${voffset 1}${goto 40}Temperature: ${font Droid Sans:style=Bold:size=8}${execpi 120 sensors | grep Core0 | paste -s | cut -c15-18 | xargs ~/.conky/colorize.sh}${hwmon 0 temp 1}°C${color}${font}${alignr}
    Here is my bash script:
    #!/bin/bash
    # colorize.sh
    COOL=65
    WARM=80
    if [[ $1 < $COOL ]];
    then
    echo "color green"
    elif [[ $1 > $WARM ]];
    then
    echo "color red"
    else
    echo "color yellow"
    fi
    exit 0
    Any help would be greatly appreciated.
    Thanks

    Using exec(p)(i) makes your conky run heavier, so, why wouldn't you use the built-in conky variables to achieve the same...
    I'm using: (before "TEXT")
    template2 ${color2}${if_match ${hwmon \1 temp \2}>75}${color orange}${if_match ${hwmon \1 temp \2}>90}${color red}${endif}${endif}${hwmon \1 temp \2}${color1}
    and i call them like: (after "TEXT")
    Temp ${template2 0 1}/${template2 1 1}/${template2 2 2}/${template2 2 4}
    Of course you need to find out what numbers you need to pass to hwmon...

  • How to send 2 variable value from bash script into java.class

    #!/bin/bash
      a=10
      b=20
       echo $a $b | java addition
    donehi there,
    currently i have a simple java coding ( a + b ). and i m trying to connect with bash script but this bash script coudln't Enter 2nd value (b=20) while i running for it. may i know how do i can Enter 2 value into it?
    output from terminal
    [seng@localhost java_class]$ bash addition.sh
    =======================================================================
    simulation 1
    Num_a       = 10
    Num_b       = 20
    Enter your Num_a : 10
    Enter your Num_b : Exception in thread "main" java.lang.NumberFormatException
       at java.lang.Integer.parseInt(java.lang.String, int, boolean) (/usr/lib/libgcj.so.6.0.0)
       at java.lang.Integer.parseInt(java.lang.String) (/usr/lib/libgcj.so.6.0.0)
       at filter_god.GOD(java.util.List, java.util.List, java.lang.String, java.lang.String, int) (Unknown Source)
       at filter_god.main(java.lang.String[]) (Unknown Source)
       at gnu.java.lang.MainThread.call_main() (/usr/lib/libgcj.so.6.0.0)
       at gnu.java.lang.MainThread.run() (/usr/lib/libgcj.so.6.0.0)
    =======================================================================

    That code will send both numbers on a single line in standard input to the java process. So if the process reads standard input, it will get a single line that has this in it: "10 20".
    I'm guessing you're sending that whole line to Integer.parseInt. But a valid number doesn't have a space in the middle.
    You should split up the line using String.split. Or use a StringTokenizer. Or a regular expression. Or you can use a java.util.Scanner. Or a java.io.StreamTokenizer. Or maybe some other stuff that has slipped my mind at the moment.

  • A bash script to backup system only with modified files

    Hi,
    I've made a simple bash script to exam which files are modified and needed to be backed up.
    It will use:
    1. the hash in Pacman's database (/var/lib/pacman/local/<pkg_ver>/files
    2. if no hash in the database, calculate it by our self from cache (/var/cache/pacman/pkg/<pkg_ver>.pkg.tar.gz
    3. if no cache found, compare build date and last modified date
    4. otherwise, this file better be backed up.
    Currently it will only print which files are needed to be backed up, but no backup actually happens. (dry run)
    And it is only in early development stage, please be careful.
    USAGE:
    <the script name> <where to backup files, a directory> <the files, or directories, separated by space, that are going to be examined>...
    Here is the code.
    #!/bin/bash
    # usage:
    # $1: file to backup
    function do_backup() {
    echo
    function smart_bak() {
    pkg=$(pacman -Qo "$1" 2>/dev/null)
    if [ 1 -eq $? ] ; then
    # No package owns $1 (locally created)
    if [ "$1" != "${1%.pacsave}" ] ; then
    echo "skip $1 (left by removed package)"
    else
    echo "backup $1 (local file)"
    fi
    else
    pkg=${pkg#$1 is owned by }
    # evaluate
    # by hash
    cur=$(md5sum $1)
    cur=${cur%% *}
    pkg_ver=${pkg/ /-}
    org=$(grep "^${1:1}" "/var/lib/pacman/local/$pkg_ver/files")
    org_hash=${org##* }
    if [ "$org" != "$org_hash" ] ; then
    # the org hash is in Pacman's database
    if [ "$org_hash" = "$cur" ] ; then
    echo "skip $1 (original config)"
    else
    echo "backup $1 (modified config)"
    fi
    else
    # no hash
    # find out hash myself?
    ARCH=$(uname -m)
    if [ -r "/var/cache/pacman/pkg/$pkg_ver-$ARCH.pkg.tar.gz" ] ; then
    org=$(tar -Oxzf "/var/cache/pacman/pkg/$pkg_ver-$ARCH.pkg.tar.gz" "${1:1}" | md5sum -)
    org_hash=${org%% *}
    if [ "$cur" = "$org_hash" ] ; then
    echo "skip $1 (original)"
    else
    echo "backup $1 (modified)"
    fi
    else
    # no cache, may be a AUR package
    # fall back to built date?
    date=$(pacman -Qi ${pkg% *} | grep "^Build Date")
    date=${date#*: }
    date=$(date -d "$date" +%s)
    mod=$(ls -l $1)
    mod=${mod% $1}
    mod=${mod#* * * * * }
    mod=$(date -d "$mod" +%s)
    tmp1=$(expr $mod "+" 60)
    tmp2=$(expr $mod "-" 60)
    if [ "$date" -le "$tmp1" -a "$date" -ge "$tmp2" ] ; then
    echo "skip $1 (the same date)"
    else
    echo "backup $1 (unknown)"
    fi
    fi
    fi
    fi
    function smart_bak_dir() {
    for i in $(ls -A "$1") ; do
    tmp="${1%/}/$i"
    if [ -f "$tmp" ] ; then
    smart_bak "$tmp"
    elif [ -d "$tmp" ] ; then
    smart_bak_dir "$tmp"
    else
    echo "skip $tmp (not a regular file nor a directory)"
    fi
    done
    # usage:
    # $1: the directory to store this backup
    # $2: directory to evalualte for backup
    # function main()
    # init
    target="$1"
    shift
    # check
    if [ ! -d "$target" -o ! -x "$target" -o ! -w "$target" ] ; then
    exit 4
    fi
    for i in $* ; do
    if [ -f "$i" ] ; then
    smart_bak "$i"
    elif [ -d "$i" ] ; then
    smart_bak_dir "$i"
    else
    echo "skip $i (unknown argument)"
    fi
    done
    Good luck,
    bsdson
    Last edited by bsdson.tw (2008-12-30 07:53:05)

    Thanks for this script. Nice work.
    Can we traverse the pacman.log backwards up and rollback each operation (including "installed" in this). Something like:
    history=$(tail -n +$(grep -m 1 -n "$1" "$LOG" | cut -d ":" -f 1) "$LOG" | tac | grep -E "(upgraded|installed)" | cut -d " " -f 3-)
    Last edited by g33k (2008-11-04 15:08:07)

  • Simple bash script to add a '-' [Solved]

    I need to write a small bash script to add a '-' to each line in a file before displaying via conky!
    Todo
    - Get Milk
    - Buy Food
    - Pay Bills
    Currently I use
    TEXT
    Todo
    ${hr}
    ${head /home/mrgreen/.stuffigottado.txt 30 20}
    In .conkyrc but have to add '-' each time I edit .stuffigottado.txt
    Thanks in advance....

    Cerebral wrote:
    To filter out blank lines, you could just modify the awk command:
    ${exec awk '!/^$/ { print "-", $_ }' stuffigottado.txt}
    very nice; awk and grep: two commands that never cease to amaze me.

  • Problem with "date -d" function in bash script. Leopard bug?

    I have this really nice rsync bash script that I use to make rotating snapshot backups of my different Ubuntu servers to a single backup server.
    I am now trying to use this same script on my Leopard machine, but it seems to have a serious problem with the following lines of code:
    lday=`date +'image-%Y-%m-%d-%H' -d '1 day ago'`
    lweek=`date +'image-%Y-%m-%d-%H' -d '1 week ago'`
    It generates the following error:
    date: illegal time format
    usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
    [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
    It's clear that it doesn't like the "-d '1 day ago'" part in my code.
    Is there a different way in Leopard to get yesterday's or last week's date in a bash script? Or is this a Leopard bug?
    Could someone please help me out? I've be trying to research this for the past 8 hours, but can't seem to find any solution to this problem.
    Thanks in advance.

    Is there a different way in Leopard to get yesterday's or last week's date in a bash script?
    date -v-1d
    date -v-7d

  • Bash script - sqllite insert problem

    So, I'm making a bash script that inserts a config file into a database, but I can't get it to work.
    This is my best attempt so far:
    name="bashrc"
    location="/home/user/.bashrc"
    content=`cat "$location"`
    sqlite3 testdb "insert into dbase values ('`echo $name`','`echo "$location"`','`echo "$content"`')"
    the table is
    create table dbase(name text, location text, data text)
    I had a hard time trying to figure out how I'd be able to get $variables to work (because of the quotes) and this echo style seems to work, but there seems to be no way to insert the config file into the database.
    plaintext files seem to work no problem, but when I'm trying to insert some config file, it spits out errors. (It seems like it's trying to execute the file somehow?)
    Last edited by initbox (2009-08-29 15:28:49)

    initbox wrote:I was thinking the single quotes were stopping bash from replacing $variables with the content, hence the echoes.
    your single quotes are inside a double quote, so to bash they're just another character in the string.
    I'm still getting an SQL syntax error, so bash is no longer getting in the way, but this thing is a true nightmare. What next? This turned out to be way harder than I expected, I'm just doing this as a "fun" learning experiment.
    Your error is probably because I was escaping the quotes for bash, and I should have been escaping them for sqlite. In sqlite, escaping a quote is done by doubling it, so ' is escaped to '' (that's two apostrephes side by side, not a double quote. Compare '' and ").
    This untested sed command might work:
    content = $(cat $location | sed "s/\'/\'\'/g")
    The \'s are escaping the quote from bash, what its really doing is replacing ' with ''.
    Dusty

Maybe you are looking for