Learning how to bash script, questions.

Hello everyone,
So I'm learning how to Bash script so I can improve my AUR packages, and also make some scripts for my personal use.
I've been working on a basic script that completely cleans your kernel source tree while saving your config file.
I was wondering if this is good and up to today's standards (Meaning checking existence of files, and checking return status for previous command):
#!/bin/bash
mv .config config
if [ -e "config" ] ; then
echo "Configuration has been backed up successfully."
else
echo "Error renaming, quitting program."
exit
fi
echo "Cleaning your kernel source tree!"
make distclean
if [ $? -eq 0 ]; then
echo "Your kernel source tree was clean successfully."
else
echo "Error cleaning your kernel source."
fi
mv config .config
if [ -e ".config" ] ; then
echo "Configuration has been installed successfully."
else
echo "Error renaming, quitting program."
exit
fi

What happens if you accidentally run it in your home directory? You probably don't want to be moving your .config folder around like this, even if it doesn't get hurt. Also, what happens if there's a pre-existing "config" file or folder? You should probably inform the user to deal with it, and bail out.
I would also consider using more verbosity, eg in the calls to "mv", and make the echo statements more descriptive and maybe use some colour.
In summary, if it were me, a first draft before playing with it more might look a bit like this:
#!/bin/bash
set -e
RED="\[\033[31m\]"
GREEN="\[033[32m\]"
BLUE="\[033[34m\]"
RESET_COLOURS="\[\033[0m\]"
CONFIG_FILE=".config"
BACKUP_FILE="config"
if [[ -f "$CONFIG_FILE" && ! -f "$BACKUP_FILE" ]]; then
printf "Backing up existing configuration: $BLUE"
mv -v "$CONFIG_FILE" "$BACKUP_FILE"
printf "${RESET_COLOURS}\n"
else
echo "Existing configuration not found or backup already exists, nothing to do."
exit
fi
printf "Cleaning kernel source tree in $(pwd) ... "
make distclean
if [ $? -eq 0 ]; then
printf "${GREEN}Success!${RESET_COLOURS}\n"
else
printf "${RED}Failed!${RESET_COLOURS}\n"
fi
if [[ -f "$BACKUP_FILE" && ! -f "$CONFIG_FILE" ]] ; then
printf "Restoring pre-existing configuration: $BLUE"
mv -v "$BACKUP_FILE" "$CONFIG_FILE"
printf "${RESET_COLOURS}\n"
else
echo "Backed up configuration not found or pre-existing configuration already there, nothing to do."
exit
fi
Last edited by /dev/zero (2012-01-13 23:03:10)

Similar Messages

  • Bash script question, how do I create multiple directories on one line

    I am making a package for amavisd-new (yes I am aware that there is one in community but I can't say I like the way it is done).
    I have an install script from which I want to create multiple directories if they do not exist.
    So I want to create a directory /var/spool/amavis with subdirectories of var tmp virusmails spammassassin .
    I can't seem to be able to find a way to do this on one line.

    pelle.k wrote:
    peets wrote:Hehe because it's less typing!
    Good one!
    Also, it's by far the more dynamic method.
    If you want to get pedantic, it's also far less efficient in terms of execution time: each iteration of the loop forks a new process, whereas using a single mkdir command forks only once.  The "best" way is the curly-braces method demonstrated above by chimeric.

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

  • First time scripting question

    Is this a situation where I should learn how to use scripting in DVD Studio?
    I have a video with 12 chapters with chapter markers. When a viewer chooses to watch an individual chapter, rather than the full video, I want a 10 second video to play before the chapter plays. It will be the same 10 second video for each of the chapters.
    Is this something scripting can do for me? Any suggestions for writing the scripts? Any suggestions for where to look for scripting lessons?
    Thanks in advance for any assistance you can provide.

    For smoothest playback, and to help with navigational issues, I would put the 10 second clip on the same track as the other material, even at the end. Though preferable in theory to have one video per track (i.e., avoid having the 10 second clip be part of the other material and not have DVD SP mux it together), it often is not that problematic.
    Otherwise you can set the end jump of the 10 second clip track to the place on the other track you would like it to go - marker, story or anywhere else on the DVD.  But again due to navigation issue, I would put them on one track.  An example of what could happen, they jump from 10 second clip track to the other track. Where does the user go if they hit the back button?  If you want them to see the 10 second clip, it becomes problematic.  If just the start of the material on the V2 track, it will send them to the beginning of the story on the track.  If you are not using stories, the back button will go through the markers until it hits the beginning of the V2 track.

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

  • Questions concerning basic bash scripting

    Good evening,
    at the moment we do bash scripting at university, but I seen to encounter some problems in understanding the functionality of bash. I would be very grateful if you guys could help me out with one or another question.
    First one:
    Task to accomplish: Scripts with three arguments. $1 -> source directory, $2 -> file suffix, $3 -> target directory. Search source directory for all files with suffix $2 and copy them to $3.
    I tried to do it, using pipe and xargs, but I am wondering how to pass the filenames found over the pipe.
    find $source -name "*.$suffix" | xargs cp [MISSING ARGUMENT] $target
    How do I access the data I need to fill in as first argument of cp, or isn't it possible to accomplish the task this way?
    Regards,
    cg

    chaosgeisterchen wrote:find $source -name "*.$suffix" | xargs cp [MISSING ARGUMENT] $target
    Almost, you just need the -t flag to cp which basically reverses the order of SOURCE and TARGET in this instance
    find $source -name "*.$suffix" | xargs cp -t $target
    Also, I suggest you escape the * in your find to prevent bash expanding it. Bash shouldn't expand, find should.
    You might like to also use the -iname (as opposed to -name) predicate to find if you don't care about the case of the source files.
    Last edited by fukawi2 (2008-06-02 03:13:37)

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

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

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

  • How can I execute a bash script by double clicking in finder

    Hello!
    How can I execute a bash script using finder? Or better: How can I create an alias, which executes my bash script?
    Thanks Johann

    Add the suffix command in your script name. E.g. Script.command.

  • How do I save a "bash" script? (in attempt to fix one of my other problems)

    Here is my original problem:
    http://discussions.apple.com/thread.jspa?threadID=2195627&tstart=0
    I came across this that sounds like it will help my issue:
    http://www.macosxhints.com/article.php?story=20090316190817357
    However, what am I supposed to do with that code? Put it in the Terminal? Save it as an Apple Script? I also got the "lingon" program set up, all I need to do is figure how how to save this "bash" script and all set!
    Any ideas?
    -Scott

    This link might help as it shows how to create the plist using lingon:
    http://mymacfixes.blogspot.com/2009/06/how-do-i-stop-clicking-noise-from-hard.ht ml

  • How to download file using ftp in bash script

    Hi! I'm runnig a bash script in solaris i want within the script to dowload file using ftp
    How can i do it?
    Tanks a lot

    hello,evgchech
    please try this way:
    1. In the bash script, try following command:
    ftp -n < ftpcmdfile2 in the ftpcmdfile (which is a file),coding the interactive commands of FTP such as:
    user anonymous  [email protected]
              cd /var/sun/download
              bi
              mget *.*
              bye
         try it and good luck!
    Wang Yu
    Developer Technical Support
    Sun Microsystems
    http://sun.com/developers/support

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

  • Hi ya'll! I'm still learning how to navigate my way with Lightroom. (Last time I wrote, I did get some responses that work. Thanks so much!) Now, I have another question. When I try to copy pics from my external drive to a CD/DVD, no matter if do it from

    Hi ya'll! I'm still learning how to navigate my way with Lightroom. (Last time I wrote, I did get some responses that work. Thanks so much!) Now, I have another question. When I try to copy pics from my external drive to a CD/DVD, no matter if do it from LR or my drive, I keep getting the message; "Disk burning is not supported by LR on this computer." I've tried everything I can think of, so, I thought I'd see if anyone may know if there's anything I can do. Or could it be that my computer just can't handle it? Help!!! So frustrating!!  I have a PC Lenovo computer, I don't know if this makes any difference. Any ideas? Thanks so much for your help!!!

    Have you burned Discs with other programs using this computer? Are you certain that you have a drive that will burn discs?

  • How do I run a bash script *before* login?

    I've got a bash script that opens an SSH tunnel that I'd like to run (as root) before any user logs in. How do I go about getting this script to run between boot and user login?
    Thanks.

    Post Unix queries to the Unix forum under OS X Technologies where those mavens frolic.

  • [DONE] Bash scripting. A few questions

    Hi,
    I've created my own custom sleep script as it is described here: https://wiki.archlinux.org/index.php/Sy … stem-sleep and it's already working correctly.
    However I've got a few questions concerning bash scripting since I've never did it before.
    Here the example from the wiki:
    #!/bin/sh
    case $1/$2 in
    pre/*)
    echo "Going to $2..."
    post/*)
    echo "Waking up from $2..."
    esac
    Now what do I need the /*) for in the cases pre and post? What does it do? And why isn't there any *) in the end which would exit the script if none of the above is true?
    Secondly, why does it say case $1/$2 in, but not case $1 in, what is the $2 needed for? E.g. in this script only $1 is used: https://wiki.archlinux.org/index.php/OS … ibernation
    And third question is, if I do really need the double quotes around $1? Does it make any difference?
    Sorry for my incompetence but I'm not a dev and as I already said I've never did any bash scripting...
    Thanks in advance
    best regards
    nuc
    Last edited by nuc (2013-02-07 18:10:56)

    ok, here's my actual code:
    #!/bin/sh
    suspend_osssound()
    /usr/lib/oss/scripts/killprocs.sh
    /usr/sbin/soundoff
    resume_osssound()
    /usr/sbin/soundon
    case "$1" in
    pre)
    suspend_osssound
    post)
    resume_osssound
    *) exit $NA
    esac
    It is the same as the one in the OSS wiki entry, but slightly configured to work under logind and not pm-utils. Of course the new location is /usr/lib/systemd/system-sleep/.
    I'm about to update the wiki with my code, so I'd like to know if there aren't any major mistakes. I tested it and it works but I want to get sure
    PS: Do people actually still use pm-utils for suspending or can I safely remove the previous script from the wiki?
    EDIT: Added double quotes
    Last edited by nuc (2013-01-25 23:42:02)

  • How to run bash script using Calendar

    Hi folks.
    How can I run a bash script using Calendar?  I thought I had to park it in an AppleScript script which I could call, but that isn't really working.
    Any suggestions appreciated.
    Cheers

    Hi there.  Thanks for the reply.
    Some notes for the replies:
    - The shell script has no environment issues.  It's a straight mysqldump for a single database.
    - The AppleScript has the do shell script "path/to/script.sh" user name "root" password "wobblyhead" with administrator privileges
    - Calendar application can only recognize the .scptd and .scpt files, and not .app files.  Upon choosing my original .scpt file with the do shell script instruction, it just opens the file in AppleScript Editor. 
    So the file gets called, but for some reason, it just opens the file and won't run the file.  No options for choosing a format where it's actually run. 
    Not sure how to go about this. 
    Cheers

Maybe you are looking for