[solved] Help with simple bash script

#!/bin/bash
current_state=cat /home/phil/.screen_state
if ["$current_state" = "laptop"];
then
disper -S
echo TV > .screen_state
else
disper -s
echo laptop > .screen_state
fi
[phil@pwned ~]$ ./screenswitch.sh
./screenswitch.sh: line 3: /home/phil/.screen_state: Permission denied
./screenswitch.sh: line 5: [: missing `]'
[phil@pwned ~]$ cat /home/phil/.screen_state
laptop
[phil@pwned ~]$
I'm not sure why I'm getting the permission denied, and also I can't see whats wrong with line 5.
Last edited by Dethredic (2011-08-21 19:46:57)

IIRC you need spaces
if [ "foo" = "foo" ]; then
between '[' and another character.
Edit: Got it.
current_state=cat /home/phil/.screen_state
This is plain wrong. I get 'Permission denied' too.
Try
current_state=$(cat /home/phil/.screen_state)
Last edited by karol (2011-08-21 17:59:16)

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)

  • Help with simple Automator script

    I have a simple Automator script for updating a specified folder with files from another folder. It consists of only two actions:
    1. Get Folder Contents (from the folder I drop on the Automator executable).
    2. Copy Finder Items.
    I left the option "replace existing files" unchecked because there's no point in replacing a bunch of files that already exist (we're talking about 4000-5000 files in the source folder).  I assumed that meant to ignore any existing files but, on the contrary, I found out that the script is copying duplicates of all the existing files -- making my target folder about 9000 files strong!
    How do I get a command into the middle of this script to restrict the Copy Finder Items command to files that do not already exist in the target folder? (It would be even nicer if it could check for files that are older than the files being copied and actually replace (only) those as well.)
    Any ideas?

    If you need the Terminal window to stay open, then you're looking at scripting Terminal. You can do this with Automator's run applescript action, or you can just use Script Editor (in Applications > AppleScript). Either way you will need to save the workflow/script as an application and drag it to your Login Items (in System Preferences > Accounts).
    click here to open this script in your editor<pre style="font-family: 'Monaco', 'Courier New', Courier, monospace; overflow:auto; color: #222; background: #DDD; padding: 0.2em; font-size: 10px; width:400px">tell application "Terminal"
    activate
    set commands to "cd /Users/lenny/ventrilo/ 
    /Users/lenny/ventrilo/ventrilo_srv"
    do script commands in front window
    end tell</pre>
    PowerMac G5 (June 2004) 2x1.8GHz 1.25GB, PowerBook G4 (12-inch DVI) 1x1GHz 768MB   Mac OS X (10.4.3)  

  • [SOLVED] Need help with simple a script.

    Hello, Iam searching for a small script that sorts my folders in alphabetical order.
    I want the script to create folder from A to Z and then move every folder that begins with A into the A folder etc etc..
    I really hope anyone understands what im searching for here.
    Last edited by nikihr (2009-09-01 20:25:33)

    scragar wrote:
    brisbin33 wrote:
    be careful, mv $I* will pick up your freshly created directory too;
    i'd `mkdir ./sorted/$I` instead, then `mv ./sorted/* ./ && rm -r ./sorted` at the end.
    you could also use
    find ./ -maxdepth 1 -iname "$I*" -exec mv {} ./sorted/ \;
    to do the actual move*
    *note: untested .
    While my `mv` code will throw an error the error will not stop the moving of the files, you'll just get 26 messages about being unable to move the directory to itself. I could probably find a way to avoid this that doesn't require the use of find(which I personally dislike) or a second dir, probably just using a file prefix like "_" or something. It would only be a small edit:
    #!/bin/bash
    for I in {a..z}; do
    echo "Moving $I";
    mkdir "_$I";
    echo "mv $I* \"$(echo $I | tr [:lower:] [:upper:])\"* _$I/";
    # mv $I* "$(echo $I | tr [:lower:] [:upper:])"* "_$I/";
    mv "_$I" $I
    done
    well, i have to politely disagree:  one, invoking find once is much better IMHO than mv with tr in a subshell.  and two, my ./sorted/ idea adds one additional mv command and one additional rm command where you're _$I suggestion added 26 additional mv commands....  just sayin'
    but we could also paint the bikeshed blue. .
    anyways, i think the OP's got more than he bargained for, hopefully we'll see a [SOLVED] on this one soon.

  • [SOLVED] Help with systemd .service script

    Hello,
    I have been using ArchLinux (ARM version) on some “plug computers” for over a year and love it.  Recently I forced myself to move to systemd by upgrading all my computers from scratch.  I migrated all my applications and learned new ways of doing things but am having trouble with one last migration.  I run a c++ communication program that monitors a TCP port for traffic.  In the past I started this program (daemon) from an entry in rc.conf.  I have read all I can about systemd’s new approach to starting daemons (https://wiki.archlinux.org/index.php/Systemd and https://wiki.archlinux.org/index.php/Systemd/Services)
    So far I created what I thought is the correct systemd .service file listed below.
    [Unit]
    Description=EQBCS
    After=network.target
    [Service]
    Type=simple
    ExecStart=/home/public/EQBCS/eqbcs -p 12947 -d &> /dev/null
    [Install]
    WantedBy=multi-user.target
    I put this file in /usr/lib/systemd/system/eqbcs.service.  I then ran the following commands in the following order:
    systemctl daemon-reload
    systemctl enable eqbcs.service (created a link in /etc/systemd/system/multi-user.target.wants)
    systemctl start eqbcs.service
    Here is output from systemctl (status)
    eqbcs.service                                 loaded failed failed    EQBCS
    I thought this would start the service but no luck.  I also thought maybe a reboot would work but no luck.  I verified I can start the daemon manually if I run /home/public/EQBCS/eqbcs -p 12947 -d &> /dev/null from the command line.
    I think I am close, but after several hours of looking at examples of .service files and other posts, I am at a loss.  I am not one of those types who posts a question without taking the time to read the wealth of information on these boards, but I am truly out of ideas and can’t figure out what to do next.  I sincerely could use some help/advice.
    Last edited by calzon65 (2013-06-01 21:18:20)

    Thank you for the suggestions, I believe I am getting closer to success. When I run systemctl start eqbcs.servcie it starts the service but the only way I can get out of systemctl is to ^c out.
    Here is my current .service file:
    [Unit]
    Description=EQBCS
    After=network.target
    [Service]
    ExecStart=/home/public/EQBCS/eqbcs -p 12947
    Type=forking
    [Install]
    WantedBy=multi-user.target
    Output from systemctl status eqbcs:
    eqbcs.service - EQBCS
       Loaded: loaded (/etc/systemd/system/eqbcs.service; enabled)
       Active: failed (Result: timeout) since Sat 2013-06-01 12:48:43 PDT; 2min 11s ago
      Process: 427 ExecStart=/home/public/EQBCS/eqbcs -p 12947 (code=killed, signal=TERM)
    Main PID: 396 (code=killed, signal=KILL)
       CGroup: name=systemd:/system/eqbcs.service
    Jun 01 12:47:13 alarm systemd[1]: Starting EQBCS...
    Jun 01 12:47:13 alarm eqbcs[427]: WARNING: Running as root NOT recommended.
    Jun 01 12:47:13 alarm eqbcs[427]: EQ Box Chat Server 10.12.18
    Jun 01 12:47:13 alarm eqbcs[427]: Waiting for connections on port: 12947...
    Jun 01 12:48:43 alarm systemd[1]: eqbcs.service operation timed out. Terminating.
    Jun 01 12:48:43 alarm systemd[1]: Failed to start EQBCS.
    Jun 01 12:48:43 alarm systemd[1]: Unit eqbcs.service entered failed state.
    Are there any other suggestions for settings in my .service file?

  • Help with a bash script, please :)

    My bash is not good, not good at all, I can't work out why this will not work.  Any help is appreciated.
    [gary@Lister ~]$ cat .bin/kiss
    #!/bin/bash
    if [ -t /tmp/kiss ]
    killall mplayer
    else
    touch /tmp/kiss
    mplayer -playlist http://www.emapdigitalradio.com/emapdigitalradio/metafiles/kiss105.asx
    fi
    errors are
    [gary@Lister ~]$ kiss
    /home/gary/.bin/kiss: line 4: syntax error near unexpected token `else'
    /home/gary/.bin/kiss: line 4: `else'
    Thanks guys

    Arkane wrote:I didn't know about disown before, but if I understood things correctly it will make the program we just started independent of the shell running the script, so that it keeps running when the shell exits.
    Yeah, the shell keeps track of its jobs, and when the shell exits, it sends a SIGHUP signal to its jobs. The "disown" command tells the shell not to bother (and stop keeping track of this job), allowing you to close the shell without disturbing the running jobs.
    You can get this effect other ways also.
    Here is a better version of the script:
    #!/bin/bash
    CMD='mplayer -playlist http://www.emapdigitalradio.com/emapdigitalradio/metafiles/kiss105.asx'
    MPID=$(ps u -C mplayer | grep "$CMD" | awk '{print $2}')
    if [ -z "$MPID" ]; then
    #echo -n starting kiss...
    $CMD &>/dev/null &
    disown %1
    #echo done
    else
    #echo -n stopping kiss...
    kill $MPID
    #echo done
    fi
    This one is less ambitious in killing all instances of mplayer. Uncomment the "echo" lines if you want some feedback.

  • Need help with simple python script (renaming and moving folder)

    I have this script for use with sabnzbd, what it does is rename all folders in the desired directory, replacing any spaces with dots (example: Movie 2011 HD -> Movie.2011.HD).
    #!/usr/bin/env python2
    workdir = '/media/stuff/movies' #### CHANGE this line to your movie directory
    for path, dirnames, filenames in os.walk(workdir):
    print "path:", path
    for dirname in dirnames:
    if dirname.find(' ') > -1 :
    # Yes, a space in the directory name, so replace it:
    newname = dirname.replace(' ','.')
    fulldirname = path + '/' + dirname
    fullnewname = path + '/' + newname
    print "Rename" , fulldirname, " ", fullnewname
    os.rename(fulldirname, fullnewname)
    What I would like it to do is 1. rename only the movie I run the script on (instead of /media/stuff/movies as above, the entire movie folder), and then 2. move the movie into /media/stuff/movies. Or vice versa! (I'd just prefer not to have it run on the entire movie directory).
    Appreciate any help!

    Just my two cents:
    I would not use walkdir but as usual a combination of find and python.
    A simplified version of the script could look like this:
    #!/usr/bin/python
    # -*- coding: utf8 -*-
    import os, shutil
    # Define target dir
    target_dir = "/media/stuff/movies/"
    # Loop through all found files
    for source_file in os.popen ("find ."):
    # Remove \n
    source_file = source_file[:-1]
    extension = source_file[-3:]
    # Only process video files
    if (extension == 'mkv') or (extension == 'avi') or (extension == 'mp4'):
    target_file = source_file.split('/')
    target = target_file[len(target_file)-1]
    target = target.replace(' ','.')
    shutil.copy (source_file, targetdir + target)
    Of course you might first want to print out instead of really copy files.

  • Help with Simple Perl script, its sooo simple!!!

    i know this isnt java but i need to know how to do this for class for this class is a prerequisite to the java servlets class. Please help, i am just starting to learn perl and this error doesnt make sence to me.
    this is my error...
    Unquoted string "cnt" may clash with future reserved word at c:\inetpub\wwwroot\ANDwebs\cgi-bin\form2.pl line 19.
    Can't modify constant item in postincrement (++) at c:\inetpub\wwwroot\ANDwebs\cgi-bin\form2.pl line 19, near "cnt++"
    Execution of c:\inetpub\wwwroot\ANDwebs\cgi-bin\form2.pl aborted due to compilation errors.
    this is my code...
    #!/usr/bin/perl -w
    print "Content-type: text/html \n\n";
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
    @fields = qw(fullName compName add1 add2 city state zip email dayPhone evePhone fax);
    @pairs = split(/&/, $buffer);
    @values;
    $cnt;
    foreach $key (@pairs)
    ($name, $value) = split(/=/, $key);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
    $value =~ s/<!--(.|\n)*-->//g;
    $values[cnt++] = $value;
    foreach $key (@fields){
    print "$key";
    }

    $values[cnt++] = $value;cnt should be $cnt.
    Also remember to always put:
    use strict;
    at the beginning of all your Perl programs!!!
    However, the fact that this is for a class that is a prerequisite for a Java class doesn't make this a Java question. Please post your Perl questions to the comp.lang.perl.* newsgroups.

  • Help With Simple if Script??

    Hi
    I have a text field named literature. In the text box i have Not Required as the default.
    At the bottom the form i want to create something that tells shipping Literature Required Yes or No.
    Basically if they leave the field literautre no touched so it says Not Required the bottom would say No but if they change it to anything else it would say Yes.
    I tried putting in a text field at the bottom of the page called litreq and tried to add in a script but i cant get anything to work.
    Here is one i tried.
    form1.#subform[0].#subform[1].litreq::initialize - (JavaScript, client)
    if 
    literature="Not Required"litreq
    ="No"
    else
    litreq
    ="Yes"

    Move the script to the exit event on literature and change the script to....
    if (literature.rawValue == "Not Required") {
        litreq.rawValue = "No";
    else {
        litreq.rawValue = "Yes";
    Steve

  • Simple bash scripting help needed..

    I want to learn som simple bash scripting in order to automate various tasks.. Im totally noob, so bear with me
    First of all I would like to set configs without using nano.. is there a simple command for this? For example if i want change my hostname in /etc/rc.conf.. how can i print the current vallue and how can i change it`?
    i was thinking something like this to get the current value:
    # cat /etc/rc.conf | grep HOSTNAME=
    which returns HOSTNAME="myhostname"
    how can i change this value with one or more commands whitout touching the rest of the file?

    abesto wrote:
    A slightly naive solution:
    CHOICE="lisa"
    NAMES="homer marge lisa bart maggie"
    if [ "`echo \" $NAMES \" | grep \" $CHOICE \"`" ]; then
    echo "this is how you do it"
    fi
    The extra spaces inside the escaped quotes are to ensure that only a whole word is "matched".
    You can also replace the elif's with a loop through a list of "the other variables". Then you'd use the loop variable instead of $CHOICE above.
    grep can check on word-bounderies with \< and \>, or with the -w switch. The -q switch suppresses any messages and exits with exit-code 0 when the first match is found:
    if echo "${NAMES}" | grep -qw "${CHOICE}"; then
    Nice and readable, should work, but i haven't tested it
    EDIT:
    Procyon wrote:CHOICE="lisa"
    NAMES="homer marge lisa bart maggie"
    if [[ $NAMES =~ $CHOICE ]]; then echo match; fi
    This one also matches elisa, ie. no check on word bounderies. You should be carefull with that
    Last edited by klixon (2009-04-23 09:40:22)

  • Solaris 11 - run a simple BASH script on computer startup

    I need to have a simple BASH script run on my Solaris 11 machine automatically whenever the computer (re)starts. It should be run with root permissions and after the computer has fully booted. What is the easiest way to do that?
    Thank you
    Dusan

    Hi user9368043
    Yes, that should be right, and be intended this way.
    See /etc/rc3.d/README and the following part from smf(5):
    Legacy Startup Scripts
    Startup programs in the /etc/rc?.d directories are executed
    as part of the corresponding run-level milestone:
    /etc/rcS.d milestone/single-user:default
    /etc/rc2.d milestone/multi-user:default
    /etc/rc3.d milestone/multi-user-server:default
    Your question concerning upgrading to Solaris 11.1:
    In the Gnome menus, you should look for (and start)
    System --> Administration --> Update Manager
    Let it do its work. It will give you a new boot environment, containing Solaris 11.1. Possibly, you have to perform upgrading twice. With "beadm activate", see beadm(1M), you can go back to Solaris 11.0 whenever you want.
    "Local" parts of your zfs root pool, like /usr/local, home directories, /root, and so on, should be in separated file systems, and be mounted outside the root pool before upgrading. They are availlable then from any boot environment, and will not be duplicated. See more in zfs(1M), zpool(1M).
    I strongly recommend upgrading. Solaris 11.1 is great.

  • Simple BASH script to update subversion files

    This is just a simple BASH script that will update all .svn files in a specified directory.  If an update fails, it will attempt to update all the subdirectories in the failed one, so as much will be updated as possible.  Theoretically, you should be able to supply this script with only your root directory ( / ), and all the .svn files on your computer will be updated.
    #! /bin/bash
    # Contributor: Dylon Edwards <[email protected]>
    # ================================
    # svnup: Updates subversion files.
    # ================================
    #  If the user supplies no arguments
    #+ then, update the current directory
    #+ else, update each of those specified
    [[ $# == 0 ]] \
        && dirs=($PWD) \
        || dirs=($@)
    # Update the target directories
    for target in ${dirs[@]}; do
        # If the target file contains a .svn file
        if [[ -d $target/.svn ]]; then
            # Update the target
            svn up $target || {
                # If the update fails, update each of its subdirectories
                for subdir in $( ls $target ); do
                    [[ -d $target/$subdir ]] &&
                        ( svnup $target/$subdir )
                done
        # If the target file doesn't contain a .svn file
        else
            # Update each of its subdirectories
            for subdir in $( ls $target ); do
                [[ -d $target/$subdir ]] &&
                    ( svnup $target/$subdir )
            done;
        fi
    done

    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.

  • Help with simple script

    I was wondering if someone could help me with a simple bit of action script 3. I need to make a movie clip (single_mc) disappear when the user clicks on the mouse (stop_btn). Here’s what I have so far.
    function setProperty(event:MouseEvent):void
    single_mc.alpha=0;
    stop_btn.addEventListener(MouseEvent.CLICK, setProperty);
    Also I was wonder if you could recommend an Action script 3 book for me. I would like one that is not a training book, but has situations and then the script written out. For example: I click a button and a movie symbol disappears from the stage. I am a graphic artist, that from time to time, needs simple interaction in flash, but cant justify the time to learn the script.
    Thanks for your time

    use the snippets panel to help with you with sample code for basic tasks.
    function setProperty(event:MouseEvent):void
    single_mc.visible=false;
    stop_btn.addEventListener(MouseEvent.CLICK, setProperty);

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

  • [SOLVED]Help with sudoers file?

    I haveing alot of trouble with my sudoers file. I would like to run the utility rkhunter as a cron job. But it must be run as root. So i wont to give myself the privledge to use it without a passwd. But when i us the line "%wheel ALL=(ALL) NOPASSWD: /usr/bin/rkhunter" it does not work. Out of curiosity i put the ALL parameter and that did not work either o,0 Either something has gone very wrong or Im in need of a lesson in sudo'ing. Can someone help? btw i looked at tutorials on the web and from what i can see im doing everything right. and before you suggest i checked that rkhunter is in /usr/bin/. here is my sudoers file.
    EDIT: removed the comment in the first line i did not have that there when i ran it.
    # sudoers file.
    # This file MUST be edited with the 'visudo' command as root.
    # Failure to use 'visudo' may result in syntax or file permission errors
    # that prevent sudo from running.
    # See the sudoers man page for the details on how to write a sudoers file.
    # Host alias specification
    # User alias specification
    # Cmnd alias specification
    # Defaults specification
    # Runas alias specification
    # User privilege specification
    root ALL=(ALL) ALL
    generic ALL=(ALL) ALL
    # Uncomment to allow people in group wheel to run all commands
    # %wheel ALL=(ALL) ALL
    # Same thing without a password
    #%wheel ALL=(ALL) NOPASSWD: ALL
    # Samples
    # %users ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
    # %users localhost=/sbin/shutdown -h now
    Last edited by generic_ (2009-06-11 13:38:41)

    rkhunter is not is /usr/sbin i checked specifically for that before i tried doing it in sudo. Its output is
    bash:/usr/bin/rkhunter: Permission Denied
    I tried your suggestion xyne with no luck. I double checked and im in the wheel group. The problem is, it is important I see the output the of rkhunter, if i didn't it would be pointless, and annoying to check the log. Also rkhunter has breaks in its output that require me to press enter to continue. So it will never finish if i dont see it. My plan is to have pop up in a terminal in front of me do its job, finish, and thats it. I was thinking I can use a simple shell script with the command. "urxvt -e rkhunter -c" Then run that shell script as a cron job. Can I get the results I want in the root crontab? Im also new to cron as well. Ive been using linux for while and I have little experience with both of these programs. Its time to learn them.
    Thanks for your effort so though,
    Last edited by generic_ (2009-06-11 11:35:41)

Maybe you are looking for

  • Where is the ENTER Button on the P1606dn when I am trying to manually feed envelopes?

    I had trouble trying to print envelopes using Microsoft Word running under Windows 7, I got an HP message saying to load the paper (envelope) then hit the ENTER button. Hitting the enter button on my keyboard did not get the intended results. Looking

  • Move BP from CRM 7.0 to ECC 6

    Hello Gurus,   We have a project to move business partners form CRM 7 to ECC 6 EhP4. We need to migrate sales area,  customer groups as well as EEWB custom fields. To map CRM EEWB fields, the table KNA1 is appended however the field names are differe

  • Somebody please help out

    Hi everyone, I'm a newbie around here, but i'm hoping it won't put anyone off helping me! in short, my problem is that i am new to web design, and have downloaded a website template which i'm trying to edit in Dreamweaver. the template i'm using is m

  • How to edit content in sample.portal

    Hi everybody, I am a newbie at Weblogic Workshop 8.1. I am trying to edit the content (in Portal Administration) of the sample.portal. I use the weblogic user (which I suppose has all the rights and privileges needed). I cannot see any content to be

  • Issues with blackberry desktop software

    whenever i connect my BB torch 9810 to BB desktop software, it shows the apps which has been installed on my phone only.. i want to installed input language and other things but it doesnot show them my phone is havin OS7.1 Regards Tushar Solved! Go t