bash script to only execute if it finds a file

Discussion in 'Programming & Software Development' started by TinTin184, Apr 23, 2012.

  1. TinTin184

    TinTin184 Member

    Joined:
    Aug 4, 2009
    Messages:
    110
    Location:
    Omicron Persei 8
    ok I have tried searching google and couldn't find anything helpful so I'm gonna try the hive mind ;)

    I'm looking for a script to check a folder for .rar files and if it finds the files to execute a script (or vis versa doesn't really matter) I thought that this script below would work but for some reason the "$?" returns "0" if it finds a .rar file or not, there may just be something wrong with the script or I might have just made a mistake somewhere and I just can't see it. Any help or input is helpful and I'm more than happy to through this script out if there is a better option available.

    Code:
    for filename in *.rar
    do
    find $2 -name '*.rar' 
    if [ "$?" -ne '*.rar' ]
    then
    echo norar >> $2/.error
    else
    #run the script
    fi
    done
    exit 0
    to explain $1 is a variable passed onto the script being run if it finds a .rar and $2 is the directory eg /home/user/folder/directory.to.be.checked
     
  2. bugayev

    bugayev Whammy!

    Joined:
    May 15, 2003
    Messages:
    4,096
    Location:
    Melbourne
    find $directory_to_look_in -name -'*.rar' -exec "$script_to_execute" {}\;

    Dont' understand why you need a script for this.
     
  3. OP
    OP
    TinTin184

    TinTin184 Member

    Joined:
    Aug 4, 2009
    Messages:
    110
    Location:
    Omicron Persei 8
    I had thought about that but I need the 2 outputs one for failing to find the file and one for finding it as the fail condition writes to a file in the directory which is then picked up by a web interface that shows me the files that where passed the checks and those that failed. That is why I need the script, its automated and goes off without me entering any commands, all I get is the end result once the script has run

    But thanks for the idea anyway :)
     
  4. tr3nton

    tr3nton Member

    Joined:
    Oct 14, 2009
    Messages:
    1,281
    $? returns the exit code of the last run program.

    http://linuxcommand.org/wss0150.php
     
    Last edited: Apr 24, 2012
  5. bugayev

    bugayev Whammy!

    Joined:
    May 15, 2003
    Messages:
    4,096
    Location:
    Melbourne
    Describe what you want to do a bit more - I am still convinced that unless it's enormously complex, you can do it in a one liner.
     

Share This Page