Pointers re bash status script

To try and come to grips with bash scripting, I have been working on a basic status script for my laptop. What I have at the moment has all the functionality that I need and, more importantly, it works.
However, as it runs in a loop and as you never know what you don't know, I would really appreciate any comments about the approach I have used.
Please don't rewrite the script, just point out things I might want to look at to make it more efficient and/or more elegant/correct. Apart from Procyon's line, most of it is stuff I have cobbled together. The $BAT stuff seems particularly kludgy...
Brutal criticism is welcome, as long as it is constructive
# edit - so much for extensive testing. Moved the $CHG line into the loop where it could actually update
#!/bin/bash
# Status script for wmfs
RED="\\#BF4D80\\"
YEL="\\#C4A1E6\\"
BLU="\\#477AB3\\"
GRN="\\#53A6A6\\"
CYN="\\#6096BF\\"
MAG="\\#7E62B3\\"
GRY="\\#666666\\"
WHT="\\#C0C0C0\\"
while true;
do
# Collect system information
CHG=`acpi -V | awk '{ gsub(/,/, "");} NR==1 {print $4}'`
BAT=`acpi -V | if grep -q "on-line"; then echo $BLU"AC"; else echo $RED$CHG; fi`
MEM=`free -m | awk '/Mem/ {print $3}'`
# CPU line courtesy Procyon: https://bbs.archlinux.org/viewtopic.php?pid=661592
CPU=`eval $(awk '/^cpu /{print "previdle=" $5 "; prevtotal=" $2+$3+$4+$5 }' /proc/stat); sleep 0.4;
eval $(awk '/^cpu /{print "idle=" $5 "; total=" $2+$3+$4+$5 }' /proc/stat);
intervaltotal=$((total-${prevtotal:-0}));
echo "$((100*( (intervaltotal) - ($idle-${previdle:-0}) ) / (intervaltotal) ))"`
HD=`df -h | awk '/^ |sd/ {if (NF==5) print $4; else if (NF==6) print $5}'`
PCM=`exec "/home/jason/Scripts/pacman-up.pl"`
INT=`host google.com>/dev/null; if [ $? -eq 0 ]; then echo $GRN"ON"; else echo $RED"NO"; fi`
DATE=`date "+%I:%M"`
# Pipe to status bar
wmfs -s 0 "$GRY[BAT $BAT$GRY] [CPU $YEL$CPU%$GRY MEM $CYN$MEM$GRY] [HDD $MAG$HD$GRY] [PAC $BLU$PCM$GRY] [NET $INT$GRY] • $WHT$DATE"
sleep 5
done
Last edited by jasonwryan (2010-12-28 06:52:25)

Thanks rockin turtle. I tried your suggestion, but couldn't get it to play nicely with the rest of the
script. So I am using Procyon's. I'm not sure what is wrong with eval, but I will live with it for the time being.
I have made quite a few changes based on everyone's input. Thank you all.
The finished product? At least for now:
#!/bin/bash
# Status script for wmfs
RED="\\#BF4D80\\"
YEL="\\#C4A1E6\\"
BLU="\\#477AB3\\"
GRN="\\#53A6A6\\"
CYN="\\#6096BF\\"
MAG="\\#7E62B3\\"
GRY="\\#666666\\"
WHT="\\#C0C0C0\\"
# Collect system information
CHG=$(acpi -V | awk '{ gsub(/,/, "");} NR==1 {print $4}')
BAT=$(grep -q "on-line" <(acpi -V) && echo $BLU"AC" || echo $RED$CHG)
MEM=$(awk '/Mem/ {print $3}' <(free -m))
# CPU line courtesy Procyon: https://bbs.archlinux.org/viewtopic.php?pid=661592
CPU=$(eval $(awk '/^cpu /{print "previdle=" $5 "; prevtotal=" $2+$3+$4+$5 }' /proc/stat); sleep 0.4;
eval $(awk '/^cpu /{print "idle=" $5 "; total=" $2+$3+$4+$5 }' /proc/stat);
intervaltotal=$((total-${prevtotal:-0}));
echo "$((100*( (intervaltotal) - ($idle-${previdle:-0}) ) / (intervaltotal) ))")
HD=$(awk '/^\/dev/{print $5}' <(df -P))
PCM=$("$HOME/Scripts/pacman-up.pl")
INT=$(host google.com>/dev/null && echo $GRN"ON" || echo $RED"NO")
DTE=$(date "+%I:%M")
# Pipe to status bar
wmfs -s "$GRY[BAT $BAT$GRY] [CPU $YEL$CPU%$GRY MEM $CYN$MEM$GRY] [HDD $MAG$HD$GRY] [PAC $BLU$PCM$GRY] [NET $INT$GRY] • $WHT$DTE"

Similar Messages

  • Problem with running Bash shell scripts

    I am unable to run Bash shell scripts on the UNIX Terminal application.
    This is the transcript from the Terminal application.
    Zhi-Yang-Ongs-Computer:/Applications/MetaPost/metapost-1.102 zhiyangong$ ./test1.sh
    dyld: Symbol not found: _BC
    Referenced from: /usr/local/bin/bash
    Expected in: /usr/lib/libSystem.B.dylib
    Trace/BPT trap
    Zhi-Yang-Ongs-Computer:/Applications/MetaPost/metapost-1.102 zhiyangong$
    Is this a problem with the the default installation of the Bash shell? Can I install the Bash shell on my own? If so, how can I do that?
    Also, how can I get the dynamic linker, dyld, to refer to the symbol "_BC"? What does this symbol "_BC" refer to?

    This was in your posted output:
    /usr/local/bin/bash
    You are NOT running the default bash, you are trying to run a private copy.
    The default Mac OS X bash is located at
    /bin/bash
    Try the following:
    /bin/bash ./test1.sh
    Does that work?
    What is the first line of your script? Is it:
    #!/bin/bash
    Or maybe
    #!/usr/bin/env bash
    /usr/bin/env would find the first bash in PATH . I find this most useful for finding perl on different systems, but sh, ksh, bash, zsh, csh, tcsh are all generally found in /bin so I do not bother using /usr/bin/env
    And if you have
    #!/usr/local/bin/bash
    Then the person that wrote test1.sh choose to use something besides the default bash
    Or maybe this script was transferred from some system where you needed to put your own copy of bash in /usr/local/bin because the vendor does not distribute bash
    Then again, you have not showed us what is inside your script, so it is possible something in the script called something else which invoked the /usr/local/bin/bash
    If that is the case, then you might try:
    /bin/bash -x ./test1.sh
    which should show you the commands executed before it died.

  • Invoking a bash shell script from Java code

    Hi All
    I am trying to invoke a Bash shell script using java code. The arguments required are "source wmGenPatch <source dir> <destination dir> no_reverse.
    in the code I have specified the arguments considering the cannonical paths of the files as the code may run on Unix or windows platform.
    I am getting a error while invoking Runtime.getRuntime().exec(args). The error is as follows :
    "The Error Occurred is: CreateProcess: source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=2"
    It seems that error=2 indicates that the 'file not found' exception. But i can see the directories referred to in the error at place in the workspace.
    Kindly advice.
    Thanks in advance.

    Hi All
    I am pretty new to invoking bash shell scripts from java and not sure if i am progressing in right direction.
    The piece of code tried by me is as follows
    try {
                   currentDir = f.getCanonicalPath();
              } catch (IOException e) {
              if (currentDir.contains("/")) {
                   separator = "/";
              } else {
                   separator = "\\";
              String args[] = new String[7];
              args[0] = "/bin/sh";
              args[1] = "-c";
              args[2] = "source";
              args[3] = currentDir + separator + "DiffEngineScripts" + separator
                        + "v4a02" + separator + "wmGenPatch";
              args[4] = sourceFileAdd;
              args[5] = destFileAdd;
              if (isReverseDeltaRequired) {
                   args[6] = "reverse";
              } else {
                   args[6] = "no_reverse";
              try {
                   Process xyz = Runtime.getRuntime().exec(args);                              
                   InputStream result = xyz.getInputStream();
                   InputStreamReader isr = new InputStreamReader(result);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ( (line = br.readLine()) != null)
                        System.out.println(line);
                   int exitVal = xyz.waitFor();
                   System.out.println("Leaving Testrun.java");
              } catch (Throwable t) {
                   t.printStackTrace();               
    and on running the same i am getting Java.io.IOException with the stack trace
    java.io.IOException: CreateProcess: \bin\sh -c source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=3
    kindly advice
    Thanks in advance

  • Bash shell script to exception when database has been shutdown

    Hi, I'm quite new in shell scripting. I created the below simple script to do a check on the database, it's a count so it works fine... if the database is there. Now I want to be able to catch if the database is or is not there, what I tried so far didn't work, can anybody please give me a hand with this?
    The shell script file "start_check.sh":
    #!/bin/bash
    # Set environmental variables
    . /home/oracle/env/usrdwh1.env
    TEMP_FILE=rwcnt
    runCheckQuery()
    # Run query and dump result into the TEMP_FILE
    sqlplus -s "/as sysdba" > /tmp/${TEMP_FILE} << EOF
    @/u02/reports/sql/start_check.sql
    EOF
    if [ $? -eq 0 ]
    then err_num=0
    else err_num=1
    fi
    ################ MAIN ####################
    runCheckQuery
    row_count=`cat /tmp/${TEMP_FILE}`
    if [ $err_num -eq 0 ]
    then
    # If no rows were found then send an email alert
    if [ $row_count -eq 0 ]; then
    echo 'No process found - Please investigate' | mailx -s "Daily check ALERT" [email protected]
    fi
    else
    # There was an error when trying to connect to the db. Need to report it
    echo 'Database connection error - Please investigate - Error Message: (' $row_count ')' | mailx -s "Daily check ALERT (Database connection error)" [email protected]
    fi
    # Remove the tmp file
    rm /tmp/${TEMP_FILE}
    The sql script file "start_check.sql":
    SET SERVEROUTPUT ON
    SET FEEDBACK OFF
    WHENEVER SQLERROR EXIT;
    DECLARE
    row_count NUMBER;
    BEGIN
    SELECT COUNT(*)
    INTO row_count
    FROM dw_ml_ba ml_ba
    WHERE sys_id = 'CCX'
    AND ml_ex_start_datetime > TRUNC(sysdate);
    DBMS_OUTPUT.PUT_LINE(row_count);
    END;
    EXIT
    Edited by: leocoppens on Jan 4, 2013 4:05 PM

    There may be a better, but here is a shell script that works:
    #!/bin/ksh
    # db_check.sh
    # Script used to check if one or all of the databases on
    # one server are available.
    # Parameter Description
    sid=$1    # Database SID or Keyword 'all'
    function check1db
    sid=$1    # Database SID
    ORAENV_ASK=NO
    . /usr/local/bin/oraenv "$sid"
    ORAENV_ASK=YES
    if [ $(ps -ef|grep "ora_smon_$sid"|grep -v grep|wc -l) -eq 0 ]
    then
      echo "%-Error, Database $sid is NOT available - Not started\n" >>${CHKLOG}
      return 1
    fi
    dbok=$(\
    sqlplus -s / <<!
    if [[ $(echo $dbok|cut -d' ' -f1 ) == 'ERROR:' ]]
    then
      echo "%-Error, Database $sid is NOT available - Started with errors\n" >>${CHKLOG}
      return 1
    else 
      echo "%-Info, Database $sid is available\n" >>${CHKLOG}
    fi
    return 0
    } # end function check1db
    # Set some environment variables:
    ORACFG=/etc               # Location of oratab
    ORALOG=$HOME/logs         # Location for result log
    EMAIL='[email protected]'  # E-mail to send alert
    sid=${sid:-'all'}
    echo "$0 Job started at: `date` "
    BDATE=$(date +%y%m%d)
    export CHKLOG=$ORALOG/db_check_${sid}_${BDATE}.log
    echo "$0 on `date`" >$CHKLOG
    if [ "$sid" = "all" ]
    then
      i=0
      stat=0
      cat $ORACFG/oratab | while read LINE
      do
        case $LINE in
         \#*)            ;;      #comment-line in oratab
            sid=`echo $LINE | awk -F: '{print $1}'`
            check1db "$sid"
            stat1=$?
            ((stat += $stat1)) # Combine the Status of All Calls
            ((i = $i + 1))     # Count Number of Databases Checked
        esac
      done
      ((j = $i - $stat))  # Count Number of Databases Available
      echo "\n%-Info, `date +%c`,\n\tTotal databases checked = $i,\n\tAvailable = $j, Not available = $stat\n" >>${CHKLOG}
    else
      check1db $sid
      stat=$?
    fi
    # Beep operator if database down.
    if [ ${stat} -ne 0 ]
    then
      SUBJ="Database(s) alert."
      mailx -s"$SUBJ" $EMAIL <$CHKLOG
    fi
    echo "$0 Job stoped at: `date` "
    exit $stat:p

  • BASH] mail-script not working

    Hi,
    Taking first steps in bash-scripting in making an autoreply-script to go along with an email-filter.
    However, this:
    /usr/bin/mail -s "Re: $1" "$2" < $EMAILMESSAGE
    Seems to give the OK-status (in an if-structure, the 'then'-statement is shown), but the mail never arrives, although it is a local mail-address. I have checked the vars (I print them in the then-statement), and they are all good.
    On the other hand, executing
    /usr/bin/mail -s test [email protected] text
    will only show me a blinking cursor. So it might be related to the mail-bin?
    Zl.

    This post gave me the idea of the following script, which seems to work properly with version 7.1 (1827) of Mail under OS X 10.9.1. The script uses GUI Scripting.
    tell application "Mail"
        activate
        tell message viewer 1
            if (preview pane is visible) then
                tell application "System Events" to tell process "Mail"
                    tell menu bar item "Mail" of menu bar 1 to ¬
                        click menu item "Preferences…" of menu 1
                    tell window 1
                        click button "Viewing" of toolbar 1
                        click checkbox "Use classic layout" of group 1 of group 1
                        click checkbox "Use classic layout" of group 1 of group 1
                        click button 1 -- close window
                    end tell
                end tell
            else
                if mailbox list visible then
                    set mailbox list visible to false
                    delay 0.5
                    set mailbox list visible to true
                else
                    set mailbox list visible to true
                    delay 0.5
                    set mailbox list visible to false
                end if
            end if
        end tell
    end tell

  • Archlinux server status script in PHP

    Screenshot: http://www.barrucadu.co.uk/server/serverstatus.png
    This script shows system information (you'll have to tweak the commands using sensors for your system), and daemons. Also displays a notice if a daemon isn't running. I've divided its display of daemons into three parts - all, services, and utilities. I've called a daemon a service if the outside world benefits directly from it, and a utility if it's more of an internal thing. For example, samba would be a service and crond a utility.
    PHP script:
    <?php
    function daemon_running($daemon)
    $checkpath = '/var/run/daemons';
    return exec("ls -l {$checkpath} | grep {$daemon}");
    $name = 'Eihort';
    $statuses = array('Northbridge fan speed' => array('', 'sensors | grep fan1 | sed -e "s/fan1:\s*\([0-9]*\).*/\\1/"', ' RPM'),
    'CPU temperature' => array('', 'sensors | grep temp3 | sed -e "s/temp3:\s*+\([0-9]*\).*/\\1/"', '°C'),
    'HDD temperature' => array('', 'sudo hddtemp -n /dev/sda', '°C'),
    'Memory usage' => array('', 'free -m | grep "buffers/cache" | sed -e "s/-\/+ buffers\/cache:\s*\([0-9]*\)\s*\([0-9]*\).*/\\1 \/ \\2/"', ' MB'),
    'Load averages' => array('', 'uptime | sed "s/.*load average: \(.*\)/\\1/"', ''),
    'Uptime' => array('', 'uptime | sed "s/.*up\s*\([0-9\:]*\).*/\\1/"', ''),
    'Package updates' => array('', '/usr/local/bin/updates', ''),
    'Logged in users' => array('', '/usr/local/bin/userson', ''));
    $services = array('bitlbee' => 'Instant messaging gateway.',
    'httpd' => 'The Apache web server.',
    'mysqld' => 'MySQL Database server.',
    'named' => 'BIND9 DNS server.',
    'openntpd' => 'Network time server.',
    'rtorrent' => 'Torrent client,',
    'samba' => 'File-sharing system.',
    'sshd' => 'Secure Shell',
    'vsftpd' => 'Very Secure FTP Daemon.');
    $utilities = array('ivman' => 'Volume manager.',
    'sensors' => 'Hardware monitor.',
    'net-profiles' => 'Network manager.',
    'crond' => 'Task scheduler.',
    'hal' => 'Hardware Abstraction Layer.',
    'dbus' => 'IPC Bus.',
    'syslog-ng' => 'System monitor.',
    'uptimed' => 'Uptime recorder.');
    $output = array('status' => array(),
    'services' => array(),
    'utilities' => array());
    foreach($statuses as $status => $details)
    $output['status'][] = array($status, $details[0] . shell_exec($details[1]) . $details[2]);
    foreach($services as $service => $description)
    $output['services'][] = array($service, daemon_running($service) ? "On" : "Off");
    foreach($utilities as $utility => $description)
    $output['utilities'][] = array($utility, daemon_running($utility) ? "On" : "Off");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
    <head>
    <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf8"/>
    <meta name="author" content="Michael Walker"/>
    <meta name="robots" content="FOLLOW,INDEX"/>
    <title><?php echo $name; ?> Status</title>
    <link rel="stylesheet" href="style.css" type="text/css" />
    </head>
    <body>
    <div id="header">
    <h1><?php echo $name; ?></h1>
    <table>
    <?php
    $half = count($output['status']) / 2;
    for($i = 0; $i < count($output['status']); $i ++)
    if($i == $half) echo '</table><table>';
    $j = ($i < $half) ? $i + $half : $i - $half;
    echo '<tr>';
    echo "<td class=\"head\">{$output['status'][$j][0]}</td>";
    echo "<td>{$output['status'][$j][1]}</td>";
    echo '</tr>';
    ?>
    </table>
    </div>
    <ul id="tabs">
    <li><a href="/">All</a></li>
    <li><a href="/?type=services">Services</a></li>
    <li><a href="/?type=utilities">Utilities</a></li>
    </ul>
    <div id="content">
    <table>
    <?php
    $pool = array_merge($output['services'], $output['utilities']);
    if(isset($_GET['type']) && isset($output[$_GET['type']])) {
    $pool = $output[$_GET['type']];
    $odd = True;
    foreach($pool as $info)
    $summary = (isset($services[$info[0]])) ? $services[$info[0]] : $utilities[$info[0]];
    echo ($odd) ?'<tr class="odd">' : '<tr>';
    echo "<td class=\"head\">{$info[0]}<br/><span class=\"summary\">{$summary}</span></td>";
    echo ($info[1] == "On") ? '<td class="good">Up</td>' : '<td class="bad">Down</td>';
    echo '</tr>';
    $odd = !$odd;
    ?>
    </table>
    </div>
    </body>
    </html>
    This is configured for my server, but I'm sure you can figure out what you need to change.
    The CSS file:
    body
    background-color:#E2E5B4;
    font-family:Liberation Sans, DejaVu Sans, Verdana, Arial, sans-serif;
    font-size:13px;
    color:#474750;
    padding:0px 0px 10px 0px;
    margin:0px;
    div#header
    border-bottom:3px solid #C8A654;
    padding:16px;
    background-color:#313D40;
    div#header h1
    display:inline;
    font-size:7em;
    color:#74B331 ;
    div#header table
    position:relative;
    right:64px;
    margin:0px 16px 0px 16px;
    float:right;
    color:#93FF20;
    border:1px solid #;
    div#header table td
    padding:3px;
    div#header table td.head
    width:200px;
    font-weight:bold;
    ul#tabs
    list-style:none;
    position:relative;
    top:-3px;
    padding:0px;
    margin:0px;
    ul#tabs li {
    float:left;
    margin:0px 16px 0px 16px;
    width:100px;
    border-left:3px solid #C8A654;
    border-right:3px solid #C8A654;
    border-bottom:3px solid #C8A654;
    background-color:#313D40;
    text-align:center;
    ul#tabs li a
    color:#FF3709;
    font-weight:bold;
    font-size:10px;
    text-decoration:none;
    ul#tabs li a:hover
    font-weight:normal;
    div#content
    clear:both;
    padding:24px 128px 0px 128px;
    margin:0px;
    div#content table
    border-spacing:0px;
    border:3px solid #C8A654;
    color:#FDFED2;
    width:100%;
    div#content td.head
    font-weight:bold;
    width:95%;
    div#content tr td
    background-color:#3E4147;
    padding:10px;
    div#content tr.odd td
    background-color:#27333A;
    div#content span.summary
    font-weight:normal;
    font-size:10px;
    div#content td.good
    color:#A4D933;
    div#content td.bad
    color:#FF3709;
    Note: in the services and utilities array it's not the name of the daemon, but the name of the file it creates in /var/run/daemons/.
    Note 2: The /usr/local/bin/updates is just a script to grab the number of updates from pacman.
    Last edited by Barrucadu (2009-07-26 14:54:28)

    I like it!
    I'll give this a crack when I get home tonight.

  • Segmentation fault calling an oracle db status script

    HI,
    I have a problem on a OEL 5 cluster with an Oracle 10.2.0.3 in active/passive environment (not RAC).
    When the Oracle Cluster service script checks the status of the service sometimes I have segmentation fault error.
    The script is:
    #!/bin/sh
    # Cluster service script to start, stop, and check status of oracle
    set -xv
    case $1 in
    start)
    su - oracle -c /home/oracle/startdb.sh
    RetVal=$?
    stop)
    su - oracle -c /home/oracle/stopdb.sh
    RetVal=$?
    status)
    su - oracle -c /home/oracle/statusdb.sh
    RetVal=$?
    esac
    set +xv
    exit $RetVal
    The error log of the executing the "status" part of the script is:
    + case $1 in
    + su - oracle -c /home/oracle/statusdb.sh
    /usr/local/sbin/oraclust.sh: line 16: 6779 Segmentation fault su - oracle -c /home/oracle/statusdb.sh
    + RetVal=139
    This script is executed every 30 seconds but I have the error once every 10 hours.
    What could it be?
    Many thanks.

    hi,
    here is the script /home/oracle/statusdb.sh:
    #!/bin/sh
    # Script to CHECK the Oracle Database Server Status.
    ORACLE_RELEASE=10.2.0
    export ORACLE_SID=mysid
    export ORACLE_BASE=/u01/app/oracle
    export ORACLE_HOME=$ORACLE_BASE/product/${ORACLE_RELEASE}/db_1
    export LD_LIBRARY_PATH=${ORACLE_HOME}/lib:$LD_LIBRARY_PATH
    export PATH=$PATH:${ORACLE_HOME}/bin
    ${ORACLE_HOME}/bin/sqlplus / as sysdba << EOF
    whenever sqlerror exit sql.sqlcode;
    whenever oserror exit failure;
    set pagesize 0;
    set feedback off;
    set wrap off;
    set heading off;
    UPDATE clustmon.clst_chk_tbl SET status = 'ok';
    commit;
    quit;
    EOF
    exit $?
    thanks.

  • Lost bash startup script

    Hi,
    I am afraid I have a stupid question to post here...
    I have lost a startup script that is invoked everytime I run my bash shell. This script starts a licence manager I no longer require or have, so everytime I run terminal an error message occurs. I could ignore this, as I get normal operation of the shell of course, however it is really annoying so I need to track down this file. I have tried using the grep command to recursively search through my harddrive for the appropriate invoking string. However to no avail.
    When I login as another user then the script doesn't run, leading me to believe it is in my own home directory. However the usual ~/.bash_profile or ~/.bashrc are not present in my home directory.
    Any tips would be appreciated.
    PowerBook G4 1.5GHz Mac OS X (10.3.9)

    Open the Terminal app then type the following:
    grep ExecutionString ~/Library/Preferences/com.apple.Terminal.plist
    If grep returns <key>ExecutionString</key> then the script is run by the Terminal's preference- com.apple.Terminal.plist. You can edit the preference removing the key and string value or trash your com.apple.Terminal.plist.

  • Bash function/script to execute multiple commands on same output

    Occasionally, I come across the need to pass the output of a single command to multiple others (without piping each to the next), so today, I wrote a [very] simple Bash script to accomplish the task.  Piping the output of a command to `tree' is much like piping it to `tee', except `tree' allows you to execute multiple commands on the same output, rather than only writing to log files:
    #!/bin/bash
    # tree -- pipes the output of one command to >= 1 other
    # Usage: command | tree 'command 1' 'command 2'
    doc=$( cat - )
    for arg in "$@"; do
    bash -c "${arg}" <<EOF
    ${doc}
    EOF
    done
    An example of its usage:
    $ echo -e "1 2 3\n4 5 6" | tree 'grep 1' 'grep 4' "grep 1 | tee grep.log | awk '{print \$2}'"
    1 2 3
    4 5 6
    2
    $ cat grep.log
    1 2 3
    Though not elaborate, the script gets the job done.
    Last edited by deltaecho (2009-03-10 20:34:01)

    Xyne wrote:
    You could always call it "the Ukrainian Pipe"
    (if you can't laugh at this, you either need to loosen up or make a point to follow (annual) current events)
    That was a good one

  • Possibly simple bash if script

    i want to have a script that mounts something then opens konqueror and then if run a second time checks if the mount is present in mtab simply opens it
    so example:
    mount -o loop /iso/test /home/user/tester
    konqueror /home/user/tester
    thats how far i know how to code (i know that aint really CODE code)
    but i want it to run a check to see if /iso/test is mounted to /user/tester then dont try to remount it but simply open konqueror
    i dont know how to make a if that checks mtab so if someone knows how i go about doing this or has a handy script i can butcher for code i would be very gratefull
    //INCSlayer

    $1,$2 ... are special bash variables used for the command line arguments,, `command hello world`;; $1=hello ...
    this might work
    #!/bin/sh
    grep "$1" /etc/mtab > /dev/null # try to find the device(server bits) in mtab;; send all stdout output to /dev/null
    if [ $? -ne 0 ]; then # if the return code($?) to the last command is not 0, then it found nothing
    # err=$(mount $* 2>&1) # uncomment this (remove '#' from the start of the line to use mount)
    # err=$(curftpfs $* 2>&1) # uncomment this and comment out the above to use curftpfs
    if [ $? -ne 0 ]; then # again, it return code isn't 0 then something went wrong
    echo "Mount Failed!"
    echo "--------------------------"
    echo $err # tell you about the actual error
    echo "--------------------------"
    exit 1 # exit if the initial mount fails
    fi
    fi
    konqueror "$2" # if all went well, start k*
    this of course assume you alway mount with said command, i.e different arguments are in the same position,,
    (incslayer.ath.cx/Music and /home/bosse/.Musik equivalents are always the first and second arguments)
    EDIT: added some comments to the code
    with this script you can copy it to two files,,
    one using the curftpfs line to mount ur server
    and one using the mount line to mount any normal devices
    read line 4&5
    Last edited by kumico (2008-04-21 23:04:35)

  • Port AppleScript to bash shell script

    Hi all,
    I made this script with the help of Neil from these forums. The purpose of the scrip is so that my friend can set up a share point on his NAS which is simply full of links so that if people access the NAS (its full of music and movies) if the delete a link, the file stays where it is.
    The issue he has now, is that when he make the links in MacOS, a Windows system will no follow them. Is there a way around this or should the script be ported to a bash script so that the links can be created internally on his BSD NAS.
    Thanks for any help and suggestions.
    set these_items to (choose file with prompt "Choose files to link:" with multiple selections allowed)
    set link_folder to (choose folder with prompt "Choose folder to place links in:")
    repeat with this_item in these_items
    tell application "Finder" to reveal this_item
    set this_path to the quoted form of the POSIX path of this_item
    set shell_folder to the quoted form of the POSIX path of link_folder
    do shell script "ln -s" & space & this_path & space & shell_folder
    end repeat
    end

    Your issue is one of symlink support, so it won't matter how you create the symlinks.
    First off, which version of Windows are you running?
    Only later versions of Windows (Win7 and, I think Vista) support symlinks, so if you're using anything earlier it won't work.
    Secondly, if you're pointing to a network volume then the target paths have to match, and that's likely to be a problem in cross-platform environments. That's because the symlink file really just contains the path to the target and your paths may be different on each OS.
    For example, On your Mac the sharepoint might be mounted at /Volumes/server and your file might be at /path/file on that share.
    So your symlink file will contain '/Volumes/server/path/file'
    No Windows system is going to be able to follow that path since disks aren't mounted under /Volumes. You would either have to know that share's current mount point or use a Windows path of the form \\server\share\path\file but that latter form won't work on non-Windows systems.
    So the short answer is that you probably have to create two sets of links, one for the Windows users and one for the Macs. There's no simple, universal, cross-platform symlink standard that will do what you want (at least that I'm aware of).

  • Bash shell scripting in Netware OS

    I've been trying to port a reporting script I had put together for out OES Linux servers to run in bash on the Netware OS servers. I've been having a few issues with bash thought, and was wondering if the issues I'm running into are just limitations of the OS, or if maybe it is handeled differently in the Netware OS implementation of bash.
    Also, another thing to note is I'm testing this on Netware 6.5 sp 8
    variables in scripts:
    ex. in linux this would work
    $variable = `df -h`
    echo $variable
    for some reason it appears that the variable is hanging up bash in netware and the command just fails.
    the other issue I've been having is if I want to string a few commands together with specific commands:
    ex:
    volumes |grep -i vol1
    this seems to hang up the whole server. I'm able to do this with other commands, but when I use volumes, I got an error " BASH: cannot duplicate fd 6 to fd 0: bad file number"
    this however isn't as big a deal as not being able to work with variables...
    has anyone else tried this that might be able to help?

    -----BEGIN PGP SIGNED MESSAGE-----
    Hash: SHA1
    > ex. in linux this would work $variable = `df -h`
    Um............. no, it wouldn't. First, you would not have a dollar
    sign at the beginning; second, no spaces around equals signs. Try the
    following:
    variable=`df -h`
    Better yet, try something really simple:
    variable=testvalue
    echo $variable
    Also keep in mind that some commands, I think volumes included, do not
    run normally within bash. If you want output from things like that you
    should probably get the contents to a file first and then grep against that.
    - From my own minimal experience with bash on NetWare also beware of
    processes that run forever (find, for example, on an entire large
    volume) as things like Ctrl+C do not seem to interrupt them well.
    It may help if you tell us what you're really trying to do. There may
    be better ways to pull this off.
    Good luck.
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v2.0.18 (GNU/Linux)
    Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
    iQIcBAEBAgAGBQJP7LfoAAoJEF+XTK08PnB5560P/314qw9tUXO5z/BVVhupV7kI
    ZzSi6u2JF6PeRIEPey0/O+jQ/i4aRs3AVWzmn+ykyk16JrFpqd4aJlOg3c0VBlYs
    /56p9u18cPbROJteF44HQC6YKwrBEjy39a4PK0cx4nTJbX9qcLz EQKst7VdvtTE5
    MeQJ3pifkOfMtKHEZPpagGyXC5vlTZpjj/CsQu8nwUb7TBlJ21o0OOhfY7P0G6HX
    E8o/qvCBTlP5PXQVfqIi+vwuYAb0pK7iUIHACwwd1P/cGSI7bA8Bp1oFz3auzwSh
    99RdGj7ZXlCjFKqpehuUE54R3b7+9njc+2eNxiaBp8jvWrn5ag 8VTQwG884zHE4n
    qW+p5tSdYbXe2LktorweTU9MhHZj/pLanE1ym8iSnk+6DTYZI8lQieLRs9LUJrlp
    cNFXh9Jxul/zGmdkoY89ddZHrDCHVRfUnsXmNDjfS5XqY55diCFKMYjM0BU5m rmC
    5tlk6EPSAFK/102e7pSpn4DWCw1WYhkwS68NuUIb/6oGHTJHo+GBCDfakLOHMhEd
    b/OvQX6EHRyo+w0Kj+DY1Ny4amViVYjy0Cahhv7L7lZ1hQTVuQBl CzNDSBuKH+8m
    sfdvTmrmHU/0j6ewtMvoB/RkLmebfhYMziFZRnahxYVJUXpejV2INzhEGC8wg84P
    I6tCX1NT0jvgP4FSf4Xv
    =Ux8a
    -----END PGP SIGNATURE-----

  • Invoking a Package.Procedure via bash shell script

    Hello All,
    I am using the below syntax to call package in a unix shell script, is this right way of calling and checking for errors or is there any other better approach?? kindly suggest.
    I am using Oracle 11g & Linux OS, SQL*Plus: Release 11.2.0.3.0 Production
       RETVAL=`sqlplus -s FCSDWH_STG/${DBSTG}@${DBSRC} <<EOF
            EXEC FCSDWH_STG.FCA_HASH_TOTALS_PKG.HASH_TOTALS_COMPUTE(${PROVIDER},${UNINUM},${EXTRACT_DT},${VER_NUM});
            EOF`
            if [ `echo ${RETVAL} | egrep "ERROR"` ]
            then
                    logit "Error While Generating The SQLPLUS Output File, Please Check"
                    exit 1
            else
                    logit "SQLPLUS Output File Has Been Generated Successfully"
            fiThanks much.

    Ariean wrote:
    I am testing the same above functionality with the below sample procedure, and I am purposefully making it compile erroneous with "dbms_output.put_lin" just for sake of testing.
    create or replace
    procedure today_is as
    begin
    dbms_output.put_lin('Today is : ' || to_char(sysdate,'DL'));
    end today_is;This is sample shell script "test.sh" I am using
    #!/bin/bash
    RETVAL=`sqlplus -s FCSDWH_STG/FCSDWH_STG@dwdev <<EOF
    set termout off
    exec today_is;
    EOF`
    echo "start here"
    echo ${RETVAL}
    echo "end here"
    if [ `echo "$RETVAL" | grep "ERROR"` ]
    then
    echo "Error While Generating The SQLPLUS Output File, Please Check"
    exit 1
    else
    echo "SQLPLUS Output File Has Been Generated Successfully"
    fiBelow is my output
    start here
    BEGIN today_is; END;
    ERROR at line 1:
    ORA-06550: line 1, column 7:
    PLS-00905: object FCSDWH_STG.TODAY_IS is invalid
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    end here
    /home/infrmtca/bin/test.sh: line 8: [: too many arguments
    SQLPLUS Output File Has Been Generated SuccessfullyI don't understand why it is printing "SQLPLUS Output File Has Been Generated Successfully" though it errored out.Because statements within backquotes are executed before the statement calling the backquote. The [ command has too many arguments coming from the echo and grep.  You might put just that test part of the script in it's own little script and test it, it seems to say that whether there is an ERROR in $RETVAL or not.  You might need to man test and see if you need a -z argument or something.
    >
    Edited by: Ariean on May 15, 2013 10:08 AM
    Edited by: Ariean on May 15, 2013 10:16 AM

  • Starting Java Program with a bash Shell script

    Hi !
    I know this is a Linux query but I am putting it on this site to get different answers.
    I want to start my Java program with a shell script. Can anybody give me a proper script to start my Java program?
    I am using RH Linux 7.3 and JDK 1.4.
    Can I start the Java program without starting the terminal? Just like the Sun One Studio4 'runide.sh' script.
    Please help.
    Bye Niteen

    assuming you have your PATH and CLASSPATH variables set correctly, your script should look like this:
    #!/bin/bash
    cd <project_dir>
    java <class> &
    example:
    #!/bin/bash
    cd ~/projects
    java project1.main_package.MainClass &
    of course you could add some more elaborated stuff like compiling files before running the program, etc.
    if you dont like terminals, try running "nautilus" (it's like Windows Explorer). i never use nautilus (especially for running scripts), so i cant guarantee it will work, although i dont see why it shouldnt...

  • Bash shell scripting

    Dear Mac Users:
    I have a bash script which I copied from a bash book to learn how to use bash. Whenever I try to run it on Linux (cygwin--Windows Linux interpreter) it throws an error that something is wrong with the syntax.
    But when I try to run the same script on my Mac using Terminal.app the bash shell throws an error saying access denied. I chowned a copy of bash and referenced this copy in my script but I still get the error. I also chowned the script to the user account on my Mac. Why can I not run the script?

    #!/bin/bash
    # cookbook filename: mkalbum
    # makalbum - make an html "album" of a pile of photo files
    # ver 2.0
    # An album is a directory of html pages.
    # It will be created in the current directory
    # An album page is the html to display one photo,with
    # a title that is the filename of the photo, along with
    # hyperlinks to the first, previous, next, and last photos.
    # ERROUT
    ERROUT()
    printf "%b" "$@"
    } >&2
    # USAGE
    USAGE()
    ERROUT "usage: %s <newdir>
    " $(basename $0)
    # EMIT(thisph, startph, prevph, nextph, lastph)
    EMIT()
    THISPH="../$1"
    STRTPH="${2%.*}.html"
    PREVPH="${3%.*}.html"
    NEXTPH="${4%.*}.html"
    LASTPH="${5%.*}.html"
    if [ -z "$3" ]
    then
    PREVLINE='<TD> Prev </TD>'
    else
    PREVLINE='<TD> Prev </TD>'
    fi
    if [ -z "$4" ]
    then
    NEXTLINE='<TD> Next </TD>'
    else
    PREVLINE='<TD> Next </TD>'
    fi
    cat <<EOF
    <HTML>
    <HEAD><TITLE>$THISPH</TITLE></HEAD>
    <BODY>
    $THISPH
    <TABLE WIDTH = "25%">
    <TR>
    <TD> First </TD>
    $PREVLINE
    $NEXTLINE
    <TD> Last </TD>
    </TR>
    </TABLE>
    </BODY>
    </HTML>
    EOF
    if (($# !=1 ))
    then
    USAGE
    exit -1
    fi
    ALBUM="$1"
    if [ -d "${ALBUM}"]
    then
    ERROUT "Directory [%s] already exists.
    " ${ALBUM}
    USAGE
    exit -2
    else
    mkdir "$ALBUM"
    fi
    cd "$ALBUM"
    PREV=""
    FIRST=""
    LAST="last"
    while read PHOTO
    do
    # prime the pump
    if [ -z "${CURRENT}" ]
    then
    CURRENT="$PHOTO"
    FIRST="$PHOTO"
    continue
    fi
    PHILE=$(basename "${CURRENT}")
    EMIT "$CURRENT" "$FIRST" "$PREV" "$PHOTO" "$LAST" > "${PHILE%.*}.html"
    #set up for next iteration
    PREV="$CURRENT"
    CURRENT="$PHOTO"
    done
    PHILE=$(basename ${CURRENT})
    EMIT "$CURRENT" "$FIRST" "$PREV" "" "$LAST" > "${PHILE%.*}.html"
    # make the symlink for "last"
    ln -s "${PHILE%.*}.html" ./last.html
    # make a link for index.html
    ln -s "${FIRST%.*}.html" ./index.html

Maybe you are looking for

  • Can I Use an Old External Hard Drive to Back Up my MacBook Pro?

    I am currently using a 2010 MacBook Pro with Snow Leopard (Mac OS X 10.6.8) and I am thinking of upgrading to Mountain Lion when it comes out. So that means I should really back up my Mac. I have never backed up my Mac before nor have I ever backed u

  • RMAN support of OPS/RAC and ISD's

    Can some one point me in the right direction for any white papers, or documentation, on RMAN and its current support of OPS/RAC and/or Intelligent Storage Devices (ISD). I'm trying to do a comparison of RMAN against other third party backup and recov

  • Backup of weblogic portal domain

    Hi, I want to know the procedure of backing up the portal domain.I have tried taking the entire domain directory and archiving it,but this didn't work. I observed that there are datasources storing the portal config data.Even at the time of archiving

  • When will ID Include Integrated Kindle .mobi Export?

    InDesign Mavens, Can anyone shed any light regarding why Adobe has yet to include Kindle .mobi generation (export) as an integrated function in InDesign? The release of InDesign CC further illuminates this problem...KDP's latest Kindle Plugin for Ado

  • Strange text corruption

    I have been having a very strange problem. I usually use outlook or outlook express to handle all my email, but I occasionally use the bt webmail facility on bt.com to read messages. With bt webmail if an incoming message contains the word submit or