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.

Similar Messages

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

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

  • Another simple bash script to clean pacman cache

    here is a simple script that I have written which cleans pacman cache folder in a way that only the packages which are now "updated" in the repositories, will get removed. This is different from what "pacman -Sc" does. pacman -Sc also removes any package which is not installed, while this script keeps all the packages which are updated whether they are installed or not.
    The functionality is some how like what "apt-get autoclean" does in debian.
    to use this script you need to run it with "list" or "clean" arguments.  you can also use the "help" argument for more help.
    I hope it helps
    #! /bin/bash
    # clcache - This script cleans pacman cache folder in a way that only the packages
    #+ which are now updated in the repositories, will get removed. This is
    #+ different from what "pacman -Sc" does. pacman -Sc also removes any package
    #+ which is not installed, while this script keeps all the packages which are
    #+ updated whether they are installed or not.
    # I have tweaked this script to be as fast as possible, it might still need a
    #+ couple of minutes to compelete based on the size of your cache folder.
    # to use this script you need to run it with "list" or "clean" arguments.
    # you can also use the "help" argument for more help.
    # This script is written by "Ali Mousavi". Please report bugs to [email protected]
    DIR="/var/cache/pacman/pkg" #the default directory of pacman cache.
    ROOT_UID=0 #Only users with $UID 0 have root privilages.
    TMPFILE="/tmp/cache.tmp"
    # Run as root
    if [ "$UID" -ne "$ROOT_UID" ]
    then
    echo "Must be root to run this script"
    exit 1
    fi
    # Check for the arguments
    if [ -z "$1" ]
    then
    echo -e 'What should I do?\nValid Argument are "list", "clean" or "help"'
    exit 1
    elif [ "$1" = "list" ]
    then
    ACTION="ls"
    MESSAGE="Are you sure you want to continue?"
    elif [ "$1" = "clean" ]
    then
    ACTION="rm -vf"
    MESSAGE="Are you sure you want to remove outdated packages? This process can not be undone!"
    elif [ "$1" = "help" -o "$1" = "-h" -o "$1" = "--help" ]
    then
    echo -e "This script checks the packages in your pacman cache directory and removes the packages that are outdated. It doesn't matter if the package is installed or not.\n\n3 arguments can be passed to the script:\n\nlist:\n\tchecks for package that are outdated and prints the names.\n\nclean:\n\tremoves outdated packages.\n\nhelp,-h,--help:\n\tprints this help text.\n\nThis script is written by \"Ali Mousavi\". Please report bugs to [email protected]"
    exit 0
    else
    echo 'Valid Argument are "list", "clean" or "help"'
    exit 1
    fi
    # Check if the user is sure!
    echo "This might take a while based on the amount of cached packages."
    echo -n "$MESSAGE(y/n) "
    read ANS
    if [ $ANS = "y" -o $ANS = "Y" -o $ANS = "yes" ]
    then
    echo "Processing packages..."
    elif [ $ANS = "n" -o $ANS = "N" -o $ANS = "No" ]
    then
    echo "Exiting on user request"
    exit 0
    else
    echo "Invalid answer"
    exit 1
    fi
    # Process the packages
    cd $DIR #change to cache directory.
    pacman -Sl | awk '{ print $2" "$3; }' > $TMPFILE
    for f in $(ls $DIR)
    do
    pname=$(file $f | cut -d: -f1) #Produces filename, like: fetchmail-6.3.19-1-i686.pkg.tar.xz"
    spname=$(echo $pname | sed 's/-[0-9][0-9]*.*//g') #removes package version: fetchmail
    pver=$(echo $pname | sed 's/.*-\([0-9\-\.][0-9\-\.]*-[0-9\-\.][0-9\-\.]*\).*/\1/g') #using pacman -Qi for all files takes a lot of time.
    if [ $(echo $pver | grep '[^0-9\-\.\-\-]' | wc -l) != 0 ] #checks if package version is alright
    then
    pver=$(pacman -Qpi $f | grep Version | awk '{print $3}')
    fi
    newpver=$(grep -e "^$spname " $TMPFILE | awk '{ print $2 }')
    if [[ $newpver != $pver ]]
    then
    $ACTION $f
    fi
    done
    rm -f $TMPFILE
    echo "Outdated packages processed successfully!"
    exit 0
    Last edited by tuxitop (2011-09-13 09:24:26)

    tuxitop wrote:# Check for the arguments
    if [ -z "$1" ]
    then
    echo -e 'What should I do?\nValid Argument are "list", "clean" or "help"'
    exit 1
    elif [ "$1" = "list" ]
    then
    ACTION="ls"
    MESSAGE="Are you sure you want to continue?"
    elif [ "$1" = "clean" ]
    then
    ACTION="rm -vf"
    MESSAGE="Are you sure you want to remove outdated packages? This process can not be undone!"
    elif [ "$1" = "help" -o "$1" = "-h" -o "$1" = "--help" ]
    then
    echo -e "This script checks the packages in your pacman cache directory and removes the packages that are outdated. It doesn't matter if the package is installed or not.\n\n3 arguments can be passed to the script:\n\nlist:\n\tchecks for package that are outdated and prints the names.\n\nclean:\n\tremoves outdated packages.\n\nhelp,-h,--help:\n\tprints this help text.\n\nThis script is written by \"Ali Mousavi\". Please report bugs to [email protected]"
    exit 0
    else
    echo 'Valid Argument are "list", "clean" or "help"'
    exit 1
    fi
    1. `echo -e 'foo\nbar\nbaz'` gets long and unreadable quickly. Instead, use here documents:
    cat <<EOF
    What should I do?
    Valid Argument are "list", "clean" or "help"
    EOF
    2. Use a case command, looks cleaner:
    case "$1" in
    list) ... ;;
    clean) ... ;;
    help|-h|--hep) ... ;;
    # Check if the user is sure!
    echo "This might take a while based on the amount of cached packages."
    echo -n "$MESSAGE(y/n) "
    read ANS
    if [ $ANS = "y" -o $ANS = "Y" -o $ANS = "yes" ]
    then
    echo "Processing packages..."
    elif [ $ANS = "n" -o $ANS = "N" -o $ANS = "No" ]
    then
    echo "Exiting on user request"
    exit 0
    else
    echo "Invalid answer"
    exit 1
    fi
    Try:
    read -p "hello: " -r
    echo $REPLY
    And again, `case` should be cleaner in this case.
    # Process the packages
    cd $DIR #change to cache directory.
    pacman -Sl | awk '{ print $2" "$3; }' > $TMPFILE
    While you quoted a lot, you left these two out. "$DIR" and "$TMPFILE" should be quoted, otherwise whitespaces will break the code.
    for f in $(ls $DIR)
    Apart from the same missing quotes, calling `ls` is a waste here. The following is sufficient and (maybe surprisingly) more accurate:
    for f in *
    How is it more accurate? Run this test script:
    #!/bin/bash
    DIR=/tmp/foo
    mkdir -p "$DIR"
    cd "$DIR"
    touch a\ b c$'\n'd
    for i in *; do
    printf '+%s+\n' "$i"
    done
    printf '%s\n' ---
    for i in $(ls $DIR); do
    printf '+%s+\n' "$i"
    done
    Let's not go too far here. Just get the idea.
    do
    pname=$(file $f | cut -d: -f1) #Produces filename, like: fetchmail-6.3.19-1-i686.pkg.tar.xz"
    Calling `file` here is, again, unnecessary. Also, filename of a package can contain ":", e.g., vi-1:050325-1-i686.pkg.tar.xz, which breaks your code.
    Don't complicate things:
    pname=$f
    spname=$(echo $pname | sed 's/-[0-9][0-9]*.*//g') #removes package version: fetchmail
    Broken for ntfs-3g-2011.4.12-1-i686.pkg.tar.xz, nvidia-173xx-utils-173.14.31-1-i686.pkg.tar.xz, etc...   Something less lousy:
    sed 's/\(-[^-]\+\)\{3\}$//' <<< "$pname"
    pver=$(echo $pname | sed 's/.*-\([0-9\-\.][0-9\-\.]*-[0-9\-\.][0-9\-\.]*\).*/\1/g') #using pacman -Qi for all files takes a lot of time.
    Although this might work for now, this would break if we had an architecture that starts with a digit, e.g. 686.  Something less lousy:
    sed 's/\(.*\)-\([^-]\+-[^-]\+\)-[^-]\+$/\2/' <<< "$pname"
    if [ $(echo $pver | grep '[^0-9\-\.\-\-]' | wc -l) != 0 ] #checks if package version is alright
    then
    pver=$(pacman -Qpi $f | grep Version | awk '{print $3}')
    fi
    Again, calling `wc` here is a waste. Anyway, why is this check necessary at all?
    newpver=$(grep -e "^$spname " $TMPFILE | awk '{ print $2 }')
    if [[ $newpver != $pver ]]
    then
    $ACTION $f
    fi
    done
    rm -f $TMPFILE
    echo "Outdated packages processed successfully!"
    exit 0
    The post is getting too long, so so much from me. If there's anything you don't understand yet, read bash(1).
    If I sound harsh or anything, don't be discouraged. Just keep reading, keep improving.
    Last edited by lolilolicon (2011-09-13 12:53:04)

  • Repcheck - A Simple Bash Script To Monitor Remote Repos Commits

    Hello all,
    I'm using a few git/svn packages from the AUR, and only recently realized that while to PKGBUILD itself is able to pull and build the latest version, the package version in the AUR will not update, unless a new PKGBUILD is pushed by the maintainer, and so my update monitor isn't aware of those remote updates.
    I've looked for a convenient way to track such changes, but all I could find were "live" monitors that run constantly and check for updates in a given repo in a set interval.
    It didn't fit my needs, so I wrote a script myself.
    The script basically maintains a file containing repo address and current revision number (for SVN) or hash (for GIT).
    Whenever an update operation is done, all remote hashes are compared to those stored in the file and if updates are found, a notification is sent.
    In case of GIT repos, the script also tries to find corresponding AUR package (I couldn't find a standard for SVN addresses...).
    It is up to the user to update currently installed version to latest remote version if he wants, script only displays notification.
    Dependencies:
    - bash
    - git
    - subversion
    - libnotify
    * EDIT *
    Updated script in next post.
    Last edited by adam777 (2013-06-14 11:55:29)

    #!/bin/bash
    RepVersionsFile=~/repversions
    TempRepVersionsFile=~/repversionsupd
    TempRepUpdatesFile=~/repupdates
    function add_to_list()
    if [ -f $RepVersionsFile ]
    then
    tmp=$(cat $RepVersionsFile | grep $1)
    if [ -n "$tmp" ]
    then
    exit
    fi
    fi
    tmp=$(echo $2 | grep ".git")
    if [ -z "$tmp" ]
    then
    current_hash=$(svn info $2 | grep Revision | awk '{ print $NF }')
    else
    current_hash=$(git ls-remote $2 | grep HEAD | awk '{ print $(NF-1) }')
    fi
    echo -e "$1 $2 $current_hash" >> $RepVersionsFile
    function remove_from_list()
    if [ ! -f $RepVersionsFile ]
    then
    exit
    fi
    tmp=$(cat $RepVersionsFile | grep -v $1)
    if [ -z "$tmp" ]
    then
    rm $RepVersionsFile
    exit
    fi
    echo -e "$tmp" > $RepVersionsFile
    function check_all()
    while read pkgname address hash
    do
    tmp=$(echo $address | grep ".git")
    if [ -z "$tmp" ]
    then
    remote_hash=$(svn info $address | grep Revision | awk '{ print $NF }')
    else
    remote_hash=$(git ls-remote $address | grep HEAD | awk '{ print $(NF-1) }')
    fi
    if [ $remote_hash != $hash ]
    then
    echo -e "$pkgname" >> $TempRepUpdatesFile
    fi
    echo -e "$pkgname $address $remote_hash" >> $TempRepVersionsFile
    done < $RepVersionsFile
    if [ -f $TempRepUpdatesFile ]
    then
    notify-send "Updates Found On Remote Repos" "`cat $TempRepUpdatesFile`"
    rm $TempRepUpdatesFile
    fi
    rm $RepVersionsFile
    mv $TempRepVersionsFile $RepVersionsFile
    case $1 in
    add-address)
    add_to_list $2 $3
    remove-address)
    remove_from_list $2
    update)
    check_all
    echo "Enter Your Choice:";
    echo "1 For Adding A Repository";
    echo "2 For Removing A Repository";
    read userchoice
    if [ "$userchoice" == "1" ]
    then
    echo "Please Enter Package Name";
    read pkgname
    echo "Please Enter Repository Address";
    read repaddress
    repcheck add-address $pkgname $repaddress
    fi
    if [ "$userchoice" == "2" ]
    then
    echo "Please Enter Package Name";
    read pkgname
    repcheck remove-address $pkgname
    fi
    esac
    Last edited by adam777 (2013-08-07 16:09:00)

  • Simple bash script in SL to remove files

    1. SL on MBP
    2. launch Terminal
    3. pico remove-files
    4. in my script are two simple rm /path to file type statements
    5. save file in user/bin directory
    6. type name of command
    7. get "command not found" error
    no wonder 99.9999% of the world doesnt program - why doesnt this simple setup work right ?

    Chris Chamberlain1 wrote:
    just guessing, if it type ./remove-files this script works.
    That's the traditional way to invoke a program or command file if its location is not in your path. If that file is in /usr/bin and /usr/bin is in your path, I'm not sure why your situation doesn't work. On my Mac the directory bin in /usr is owned by root:wheel. If yours is the same, how did you manage to create your script there without permission manipulations? What exactly did you mean when you first mentioned "save file in user/bin directory"? Did you really mean /usr/bin or something else? If you meant some other location, you might want to add that location to your path with this command:
    PATH=yourotherdirectory:$PATH

  • Simple Shell Script To Add To Default Path?

    I know that this question will at first appear idiotic,but here goes.
    I'm logged into a Solaris 9 shell as 'root'. I echo $PATH and see a couple of default paths. I want to add to that PATH - this can easily be done from the command line as follows:
    PATH=$PATH:/some/other/path
    export PATH
    So, naturally, I'd like to throw this into a simple script, and when I do so, and run the script called 'hello'. So, I run 'hello' as follows:
    ksh hello (I'm a kshell)
    Result: no errors. Then, I check my PATH as follows:
    echo $PATH
    And nothing changes, it's still the same PATH!
    Can anyone tell me how to do this?
    Appreciate your response.
    dedham_ma_man

    The question shows you don't really understand how shells work.
    The path is part of the environment of your current shell.
    Any command you "execute" is run in a new process. And any changes made to the environment of that process cannot effect the environment of the parent process (ie your shell).
    So by saying "ksh hello" your starting a new shell and changing the path in that shell. But when that shells exits and your back in the original shell, of course nothing has changed.
    So the answer is that what you have to do is not "run" the script. But persuade your current shell to execute in its own context.
    In a C shell that would be done by the "source" command. And in a bourne shell, its the "." command. But I'm not sure how you do it in korn shell.

  • Multiarchive RAR bash script (SOLVED)

    Dear Fellow Archies!
    I use the command
    rar a -w<working_folder> -m5 -v<max_volume_size> <archive_name> <target_file_or_folder>
    whenever I need to make a multiarchive rar file, because I have not yet found a GUI archive manager that does this.
    So, I've decided to write a simple bash script to make things easier.
    Here's the script:
    #!/bin/bash
    echo Please, enter the full path to the target file or folder [without the target itself]!
    read PATH
    echo Please, enter the target filename [with extension] or folder name!
    read TARGET
    echo Please, enter the desired archive name [without extension]!
    read DESTINATION
    echo Please, enter the desired volume size in KB!
    read SIZE
    rar a -w$PATH -m5 -v$SIZE $DESTINATION $TARGET
    Executing the last line of the code in terminal works without any hassle. When I run this entire script however, it doesn't.
    What needs to be changed for the script to work?
    RAR man page is HERE - CLICK, in case someone needs to take a look at something.
    Thank you and thank you,
    UFOKatarn
    Last edited by UFOKatarn (2012-05-03 07:38:28)

    Done! Working!
    Geniuz: Logout-login did it. How simple.
    Juster: I added "echo $PATH" to the script and ran it with "bash -x". And the output was the same as after the logout-login. Here it is, in case you are curious.
    /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/bin/core_perl:/opt/qt/bin
    Thank you all for your help guys :bow:.
    OFFTOPIC:
    All who intend to use Xfce launchers to run bash scripts: There are two options in the settings for each launcher: "Command" and "Working Directory". And when I had "Working Directory" filled with "/home/username/", the script didn't work. It worked perfectly after I blanked out the "Working Directory" option. Just so you know, in case someone doesn't .
    This has never happened to be before, but still, I guess it is better to do it with blank "Working Directory" and entering the entire path into the script in the "Command" field. It might be that Xfce launchers always stick to the "Working Directory", even though a script might tell them otherwise.
    Last edited by UFOKatarn (2012-05-03 07:38:05)

  • Using Bash script to edit config file

    This is a really simple question, but given that I'm just learning Bash scripting and having this solved now would be really illustrative for me, I would really thank some help here.
    I'm using uzbl, and running Tor+Polipo. So, as you will see below in the tail of the config file, there is a line to redirect the requests of uzbl through Polipo.
    # === Post-load misc commands ================================================
    sync_spawn_exec @scripts_dir/load_cookies.sh
    sync_spawn_exec @scripts_dir/load_cookies.sh @data_home/uzbl/session-cookies.txt
    # Set the "home" page.
    #set uri = https://duckduckgo.com
    # Local polipo proxy
    set proxy_url = http://127.0.0.1:8123
    # vim: set fdm=syntax:
    What I want to accomplish is to comment in/out that line with a key shortcut on Awesome. I've thought of doing 2 scripts to do so and using 2 differente key shortcuts, but I want to "toggle" the proxy redirection with only 1 shortcut. To do so, I suppose that the script should go something like:
    if
    tool 'set proxy_url = http://127.0.0.1:8123' config_file
    then
    tool '#set proxy_url = http://127.0.0.1:8123' config_file
    else
    if
    tool '#set proxy_url = http://127.0.0.1:8123' config_file
    then
    tool 'set proxy_url = http://127.0.0.1:8123' config_file
    fi
    fi
    I know little about sed, but I think is the tool for this job. The most intriging part to me is to ask sed to print the regular expression when it finds it in the config file, and use that as an input in the conditional statement.
    Well, this is a mess I have done here. Hope there is a simple answer to this.
    Thanks in advance.-

    You can do this with a single sed command:
    sed -i 's/^#set proxy_url/set proxy_url/;
    t end;
    s/^set proxy_url/#set proxy_url/;
    : end' config_file
    This edits the file in-place (-i) and first tries to replace the commented with the uncommented line. If that suceeds, sed jumps to the "end" label. If not, it tries to replace the uncommented with the commented line. Thus you don't have to include any logic about the current state: if the first substitution succeeds, the line was obviously commented, if not, it was uncommented, and the second substitution should succeed.
    Note that my knowledge of sed is very limited. There might be a simpler way to do this.
    EDIT: For the sake of example, here's how to do the same in bash using regular expressions. Note how this script needs to use a temporary file to simulate in-place editing, how it needs to process the file line by line manually, etc. All things that sed does out of the box...
    #!/bin/bash
    tmp=test.conf.tmp
    echo -n "" > "$tmp"
    while read line; do
    if [[ "$line" =~ ^#set\ proxy ]]; then
    echo "${line/\#/}" >> "$tmp"
    elif [[ "$line" =~ ^set\ proxy ]]; then
    echo "#$line" >> "$tmp"
    else
    echo "$line" >> "$tmp"
    fi
    done < test.conf
    mv test.conf.tmp test.conf
    To answer your original question, the line
    if [[ "$line" =~ ^#set\ proxy ]]; then
    reads: if the line begins with a "#", followed by "set proxy", then...
    Last edited by hbekel (2011-03-20 10:40:16)

  • Iwl3945 and dhcpcd workaround - bash script

    I got tired of typing every command by hand all the time, so i made this simple bash script to do this for me...
    edit the script with your preferences and settings and run it as root. The script sets a static ip, and all the shizzle thats needed to have a workaround for the dhcp not working
    And im a newbie in bash programming, so please dont flame
    anywho, please give med feedback if theres something i could do different and better
    wlan script

    Correct me if I'm wrong, but you could simply add the rmmod / modprobe stuff and all that in PRE_UP='' in any of your netcfg profiles and the just run netcfg <profile>.

  • Sudo Command in Bash Script

    So I created a simple bash script to run on login.....
    one of the commands is the following:
    sudo "something something something"....
    One thing I haven't learned in my years of Unix is how do you get a bash script to run a sudo command without having to enter a password?  I know this is trival, but just a quick 'this is how you do it' would be cool.
    Thanks ahead of time on this really dumb question.

    There's a few ways to do this.  Here's two (pick the method you like):
    Method 1: Using "askpass".
    With this you always do sudo -A command.  The -A argument tells sudo to execute a command that echos the password to stdout.  That command is something you write.  For this explaination let's call the command pw and stick it /usr/local/bin.  So it's full pathname would be /usr/local/bin/pw.
    sudo -A can get the pathname to pw a number of ways.
    1. From the sudoers file.
    Use visudo to add the following line to the sudoers file:
    Defaults:ALL    askpass=/usr/local/bin/pw
    2. Using the SUDO_ASKPASS environment variable.
    export SUDO_ASKPASS=/usr/local/bin/pw
    This might work too (assuming SUDO_ASKPASS has been previously exported):
    SUDO_ASKPASS=/usr/local/bin/pw sudo -A command
    Method 2: Have sudo read the password from stdin
    echo -n password | sudo -S command
    The -S option tells sudo to read the password from stdin so echo pipes it in (without the ending newline).
    The only relatively secure scheme of these two methods is the askpass (-A) method.  At least with that method you have a chance of encrypting/hiding your password down in the command that echoes it to stdout.  The -S method would contain your password explicitly in a script somewhere unless you make other provisions to encrypt/hide it with that technique.

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

  • BASH Script - Launch App with

    I'm trying to write a simple BASH script that will laungh an program, but that program needs command line arguments.
    When I put it in quotes it says it can't find the file, if I don't use quotes then it won't run the program with the command line arguments. How can I launch a program using a BASH script with command line arguments?
    Thanks in advance

    #!/bin/bash
    /Users/name/Desktop/Directory/app -f configfile

Maybe you are looking for