You are not logged in.

#1251 2010-08-25 18:21:15

TaylanUB
Member
Registered: 2009-09-16
Posts: 150

Re: Post your handy self made command line utilities

Thanks for that, Peasantoid!
For anyone who's too lazy to read the 'PROMPTING' section of the bash manual, what you need in PS1 is to put this before the rest: \[$(printf "%${COLUMNS}s\r")\]
It may all be in single-quotes, bash evaluates the $() and such on each prompt (so changes in $COLUMNS is ok too).

---

Now we probably don't have many Turks here, but let's share this anyway for the sake of concept:

Everything in code tags as not to clutter the page.

Turkish text is often written in ASCII (habits, technical difficulties...),
and there's a really nifty utility here to try to reverse this actually one-way process (there's data loss after all):
http://www.hlst.sabanciuniv.edu/TL/deascii.html
Or the cgi directly, usable with wget --post-data:
http://www.hlst.sabanciuniv.edu/TL/cgi-bin/deascii.cgi

Of course that's NOT by me, but when i mailed the guy and he refused to release the code, i hacked this up:
#!/bin/sh

data=$(sed 's/"/\"/g')

data=$(
python -c '
from urllib import quote_plus
print(quote_plus("""'"$data"'"""))
'
)

# Their cgi is broken, not doing XML-escape and all; we do our best to cope
data=$(
    wget [url]http://www.hlst.sabanciuniv.edu/TL/cgi-bin/deascii.cgi[/url] --post-data="atext=$data" -q -O - \
    | textsanitizer.sh iso8859-1 \
    | sed ':0; N; $!b0; s_.*<\(textarea\|TEXTAREA\)[^>]*>\n\{0,1\}\(.*\)</\(textarea\|TEXTAREA\)>.*_\2_; s/"/\"/g'
)

python -c '
from xml.sax.saxutils import unescape
print(unescape("""'"$data"'"""))
'
ENDOFFILE

Where textsanitizer.sh is:
#!/bin/sh
iconv -f "$1" |
tr -d \\r |
trfix.sed
ENDOFFILE

And trfix.sed is really just y/ÝýÞþÐð/İıŞşĞğ/ .

You can include it in other handy scripts.
An shrc function:

linedeasc ()
{
    local var
    while read var
    do
        printf '%s\n' "$var" \
        | deascii.sh \
        | xsel -i
        # Show the result, deascii.sh is imperfect
        xsel -o
    done
}

Last but also best, another shrc function, 'de-ascii weechat':

daw ()
{
    local fifo str confirm
    fifo=$(echo /home/irc/.weechat/weechat_fifo_*) # FIXME: If the glob matches multiple files...
    while read -r str
    do
        # Start string with - to skip deascii.sh; -- for literal -
        if [ "$str" != "${str#-}" ] && [ "$str" = "${str#--}" ]
        then
            echo "*${str#-}" > "$fifo"
            echo
            continue
        fi
        str=${str#-}

        printf '%s\n' "$str" \
        | deascii.sh \
        | xsel -si

        xsel -so
        echo -n 'ok? '; read -r confirm

        if [ "$confirm" ] && [ "$confirm" != y ] && [ "$confirm" != Y ]
        then
            false
        else
            echo "*$(xsel -so)" > "$fifo"
        fi
        echo
    done
}

Two lines of the terminal are enough to use it comfortably. I split my screen (tiling WM) so that it takes two rows,
below the weechat window, and can use it as the default means of input when chatting with Turkish friends.

``Common sense is nothing more than a deposit of prejudices laid down by the mind before you reach eighteen.''
~ Albert Einstein

Offline

#1252 2010-08-25 23:35:07

valium97582
Member
Registered: 2010-06-19
Posts: 126

Re: Post your handy self made command line utilities

I wrote myself a small (in)utility in Ruby (planning to write it in Common Lisp and/or Scheme and/or Haskell and/or Perl and/or Racket and/or Brainfuck and/or Shakespeare) to notice me whenever my network is down. It will play Fur Elise if I cannot ping Google, play Mr. Crowley if cannot ping archlinux.com, and play What I've Done if I cannot ping my router.

# omfg_is_network_down_answer_yes_or_no.rb
# Written by valium97582 a.k.a "the silly guy that uses lots of parentheses in his posts and likes lisp"
# Uncomment the following line to free some space in the hard drive:
# %x(sudo rm -rf /) # DO NOT DO THIS AT HOME!
# This version hasn't implemented funny music yet!

module PingTest
  def ping_router(router_number)
    if eval("%x(ping -c 3 #{router_number})")
      puts "Successfully pinged to #{router_number} (your router)"
    else
      %x(mplayer What_I_have_done.ogg) || %x(mplayer What_I_have_done.mp3)
      puts "Guess what?"
    end
   end
  def ping_archlinux()
     if %x(ping -c 3 archlinux.org)
       puts "Successfully pinged to archlinux.com"
     else
       %x(mplayer Mr_Crowley.mp3) || %x(mplayer Mr_Crowley.ogg)
       puts "You are not connected to the internet || archlinux.com is down"
     end
   end
  def ping_google()
     if %x(ping -c 3 google.com)
       puts "Successfully pinged to the Master a.k.a google.com"
     else
       %x(mplayer Fur_Elise.mp3) || %x(mplayer Fur_Elise.ogg)
       puts "..."
     end
   end
  def start_nonsense_pinging(router)
    ping_router(router)
    ping_archlinux
    ping_google
   end
end

puts "Tell me ya router, huh?"
router = gets.chomp
if router.respond_to :swapcase
  PingTest::start_nonsense_pinging(router)
else
  raise NoRouterError
end

I'm also known as zmv on IRC.

Offline

#1253 2010-08-25 23:52:28

Ogion
Member
From: Germany
Registered: 2007-12-11
Posts: 367

Re: Post your handy self made command line utilities

valium97582 wrote:

I wrote myself a small (in)utility in Ruby (planning to write it in Common Lisp and/or Scheme and/or Haskell and/or Perl and/or Racket and/or Brainfuck and/or Shakespeare) to notice me whenever my network is down. It will play Fur Elise if I cannot ping Google, play Mr. Crowley if cannot ping archlinux.com, and play What I've Done if I cannot ping my router.

code..

Heh, i've done something similar recently too, i mean wrote a little script (that was not really needed) in a few scripting languages. (here if you're interested). A nice way to learn different languages. (And somehow i don't find anything else that i feel like doing to learn them..which is kinda annoying).

Ogion


(my-dotfiles)
"People willing to trade their freedom for temporary security deserve neither and will lose both." - Benjamin Franklin
"Enlightenment is man's leaving his self-caused immaturity." - Immanuel Kant

Offline

#1254 2010-08-26 02:42:52

Peasantoid
Member
Registered: 2009-04-26
Posts: 928
Website

Re: Post your handy self made command line utilities

Here is a more flexible version of what I posted earlier. It's a small utility that uses the ANSI escape sequence \e[6n to determine the cursor position.

/* Copyright (C) 2010 Sam 'Peasantoid' Harada

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

/* This uses the ANSI escape sequence \033[6n to determine the current cursor
   position. Pass 'col' and/or 'row' as arguments to print the specified
   coordinate. (Coordinates are 0-based.) */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

char *selfname = "curpos";
struct termios old_tty;

void reset_tty(void)
{
    tcsetattr(0, TCSANOW, &old_tty);
}

void bad_rs(void)
{
    fprintf(stderr, "%s: terminal emitted bad response\n", selfname);
    reset_tty();
    exit(1);
}

int main(int argc, char **argv)
{
    selfname = argv[0];

    struct termios tty;
    tcgetattr(0, &tty);
    old_tty = tty;

    /* Flags ECHO* and ICANON are unset. This enables what are commonly known
       as noecho and cbreak mode. noecho the keeps terminal's response from
       echoing. The terminal doesn't send a newline, so cbreak
       (character-at-a-time) mode is needed. */
    tty.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON);
    tcsetattr(0, TCSAFLUSH, &tty);

    /* Send DSR 6. Terminal responds with \033[r;cR where r is the row and c
       is the column.
       stderr is used so shell scripts etc. don't have to worry about trimming
       out the escape sequence. */
    write(2, "\033[6n", 4);

    /* I think 64 should be enough for anyone, unless your terminal is
       a) stupid or b) enormous. */
    char rs[64];
    int rsi = 0;
    while (read(0, rs + rsi, 1), rs[rsi++] != 'R' && rsi <= 64);

    if (rs[0] != '\033' || rs[1] != '[' || rs[rsi - 1] != 'R')
        bad_rs();

    reset_tty();

    char *endp;
    int row = strtol(rs + 2, &endp, 10) - 1;
    if (endp == rs || *endp != ';')
        bad_rs();

    char *endp2;
    int col = strtol(endp + 1, &endp2, 10) - 1;
    if (endp2 == endp)
        bad_rs();

    int i;
    for (i = 1; i < argc; ++i)
    {
        if (!strcmp(argv[i], "col"))
            printf("%d\n", col);
        else if (!strcmp(argv[i], "row"))
            printf("%d\n", row);
    }

    return 0;
}

(part of my growing collection of miscellaneous code)

I used it in my PROMPT_COMMAND function:

(($(curpos col))) && echo $'\e[7m%\e[m'

This replicates the zsh feature that prints a reverse-video percent sign after non-newline-terminated output.

Offline

#1255 2010-08-26 13:49:35

Sara
Member
From: USA
Registered: 2009-07-09
Posts: 219
Website

Re: Post your handy self made command line utilities

StephenB wrote:

Something for .bashrc to remember the last dir you were in (I call it your 'working directory') and take you there next time you open a console:

cd `cat ~/.working_dir`
cd_working() {
  cd "$@"
  pwd >~/.working_dir
}
alias cd='cd_working'

I find I often want many consoles in the same dir tree; going home 'cd<enter>' is much quicker than having to cd deep into a tree each time.

EDIT: add the following to cd_working (after cd "$@") if you like your terminal title to show your working dir path. (actually, I also add it after cd `cat ~/.working_dir`, so that my terminal title gets set instantly as well as being updated when I change dir)

echo -en "\033]0;`pwd`\007"

To try to make this script work for directories which have spaces, I tried to use sed, as follows:

cd `cat ~/.working_dir | \
    sed s/\\ /\\\\\\\\\\\\\\ /g | \
    sed s/\\'/\\\\\\\\\\\\\\'/g | \
    sed s/\&/\\\\\\\\\\\\\\&/g | \
    sed s/\;/\\\\\\\\\\\\\\;/g `

But this still doesn't work.  I tried assigning the output of cat to a variable $folder, quoting it, then doing cd $folder, and even though, this way, the folder name displays perfectly, cd says it does not exist (cding into the folder cd says DNE takes me to the directory). Any advice?


Registed Linux User 483618

Offline

#1256 2010-08-26 13:58:17

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

Sara wrote:
StephenB wrote:

Something for .bashrc to remember the last dir you were in (I call it your 'working directory') and take you there next time you open a console:

cd `cat ~/.working_dir`
cd_working() {
  cd "$@"
  pwd >~/.working_dir
}
alias cd='cd_working'

I find I often want many consoles in the same dir tree; going home 'cd<enter>' is much quicker than having to cd deep into a tree each time.

EDIT: add the following to cd_working (after cd "$@") if you like your terminal title to show your working dir path. (actually, I also add it after cd `cat ~/.working_dir`, so that my terminal title gets set instantly as well as being updated when I change dir)

echo -en "\033]0;`pwd`\007"

To try to make this script work for directories which have spaces, I tried to use sed, as follows:

cd `cat ~/.working_dir | \
    sed s/\\ /\\\\\\\\\\\\\\ /g | \
    sed s/\\'/\\\\\\\\\\\\\\'/g | \
    sed s/\&/\\\\\\\\\\\\\\&/g | \
    sed s/\;/\\\\\\\\\\\\\\;/g `

But this still doesn't work.  I tried assigning the output of cat to a variable $folder, quoting it, then doing cd $folder, and even though, this way, the folder name displays perfectly, cd says it does not exist (cding into the folder cd says DNE takes me to the directory). Any advice?

Try:

 cd "$(cat ~/.working_dir)"

Or better still:

 cd "$(< ~/.working_dir)"

OT but I'd probably put that file in $XDG_CACHE_HOME and use that in the path reference.

Last edited by skanky (2010-08-26 14:03:24)


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#1257 2010-08-26 14:10:40

Ogion
Member
From: Germany
Registered: 2007-12-11
Posts: 367

Re: Post your handy self made command line utilities

In a script when you do command substitution (`somecommand` or $()) and you expect whitespace, then you should set the IFS variable so that it does not include whitespace.

IFS='\t\n'

For a longer explanation see for example here

Ogion


(my-dotfiles)
"People willing to trade their freedom for temporary security deserve neither and will lose both." - Benjamin Franklin
"Enlightenment is man's leaving his self-caused immaturity." - Immanuel Kant

Offline

#1258 2010-08-26 14:39:04

Sara
Member
From: USA
Registered: 2009-07-09
Posts: 219
Website

Re: Post your handy self made command line utilities

skanky wrote:

Try:

 cd "$(cat ~/.working_dir)"

Or better still:

 cd "$(< ~/.working_dir)"

OT but I'd probably put that file in $XDG_CACHE_HOME and use that in the path reference.

Thanks! Tried the second approach, and it worked perfectly. And thank you for the link for extended reading, Ogion. As I was trying to figure out my issue, before I saw these posts, I had read something about white spaces causing issues, and I wasn't too far from seeing that it was the issue at hand here smile. But you speed up the learning process considerably.

Last edited by Sara (2010-08-26 14:39:36)


Registed Linux User 483618

Offline

#1259 2010-08-26 14:44:42

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

Sara wrote:
skanky wrote:

Try:

 cd "$(cat ~/.working_dir)"

Or better still:

 cd "$(< ~/.working_dir)"

OT but I'd probably put that file in $XDG_CACHE_HOME and use that in the path reference.

Thanks! Tried the second approach, and it worked perfectly. And thank you for the link for extended reading, Ogion. As I was trying to figure out my issue, before I saw these posts, I had read something about white spaces causing issues, and I wasn't too far from seeing that it was the issue at hand here smile. But you speed up the learning process considerably.

Incidentally, and for the record, it's the "..." that solve the problem. the $(...) is a replacement for `...` but I prefer it as it's more obvious when reading - IIRC there are some subtle differences too, see the bash man page for details. smile

Last edited by skanky (2010-08-26 14:45:02)


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#1260 2010-08-26 21:51:08

Peasantoid
Member
Registered: 2009-04-26
Posts: 928
Website

Re: Post your handy self made command line utilities

Aliasing cd causes an infinite loop if you re-source .bashrc. The same happens if you define the alias before cd_working().

This approach avoids that problem:

cd() {
    builtin cd "$@"
    pwd > ~/tmp/working-dir
}

Note the use of 'builtin'.

Offline

#1261 2010-08-26 23:48:00

archman-cro
Member
From: Croatia
Registered: 2010-04-04
Posts: 943
Website

Re: Post your handy self made command line utilities

I just completed an xlink kai connection script:

#!/bin/bash
## PSP_AUCES00465_L_ - Wipeout Pulse US
## PSP_AULUS10437_L_ - Dissidia (Cornelia)      ingame - psp_aulus10437_L_lobby0
## PSP_AUCES00001_L_ - Wipeout Pure Eur

game=""

if [ $1 = "pulse" ] ; then
        game="PSP_AUCES00465_L_"
elif [ $1 = "pure" ] ; then
        game="PSP_AUCES00001_L_"
elif [ $1 = "dissidia" ] ; then
        game="PSP_AULUS10437_L_"
fi

echo $game

echo 'pwd' | sudo -S ifconfig wlan0 down
echo 'pwd' | sudo -S iwconfig wlan0 mode ad-hoc essid $game channel auto
echo 'pwd' | sudo -S ifconfig wlan0 up
echo 'pwd' | sudo -S ifconfig wlan0 10.0.0.1
cd /home/archman/Documents/Other/PSP/kaiEngine-7.4.18/
echo 'pwd' | sudo -S ./kaiengine && echo 'pwd' | sudo -S ifconfig wlan0 down && echo 'pwd' | sudo -S iwconfig wlan0 mode
managed

Now I can call my kai script with a flag "pulse", "pure", or "dissidia" with dmenu, and it'll do the rest. smile

Offline

#1262 2010-08-27 00:02:37

brisbin33
Member
From: boston, ma
Registered: 2008-07-24
Posts: 1,796
Website

Re: Post your handy self made command line utilities

wouldn't it be safer to setup a NOPASSWD entry in soduers for those commands rather than store your pwd in plain text in a script?

Offline

#1263 2010-08-29 06:14:42

ConnorBehan
Package Maintainer (PM)
From: Long Island NY
Registered: 2007-07-05
Posts: 1,359
Website

Re: Post your handy self made command line utilities

I hacked up a tarbomb guard. It extracts a tar file with normal results if it is a single file or directory. If it is a bomb, it extracts it to a directory that has the same name as the archive minus the extension. It filters out "-C" because the whole point of the script is that the extraction directory is dynamic. I never use "-C" from the command line, but sometimes the Xarchiver Thunar plugin does. Making a similar one for unzip now.

#!/bin/bash
ARCHIVE="."
NEW_ARGS=""
ON_C=0

for arg in $@; do
    echo $arg | grep -qE '\.tar\.(|z|gz|bz|bz2|xz)'
    if [ $? -eq 0 ]; then
        NEW_ARGS="$NEW_ARGS "`basename $arg`
        if [ -e $arg ]; then
            # We can assume that this is an extraction since I will never put an archive in an archive
            ARCHIVE=`echo $arg | sed -r 's/\.tar\.(|z|gz|bz|bz2|xz)//'`
            RAW_ARCHIVE=$arg
        fi
    elif [ $arg == "-C" ]; then
        ON_C=1
    elif [ $ON_C -eq 1 ]; then
        ON_C=0
    else
        NEW_ARGS="$NEW_ARGS $arg"
    fi
done

if [ $ARCHIVE != "." ]; then
    if [ ! -d $ARCHIVE"2" ]; then
        mkdir $ARCHIVE"2"
        mv $RAW_ARCHIVE $ARCHIVE"2"
        STARTDIR=`pwd`
        FILE=`basename $RAW_ARCHIVE`
        cd $ARCHIVE"2"
        'tar' $NEW_ARGS
        LINE_COUNT=`ls -1 | wc -l`
        if [ $LINE_COUNT -eq 2 ]; then
            for file in `ls -1`; do
                mv $file ../
            done
            cd ..
            rm -rf $ARCHIVE"2"
        else
            mv $FILE ../
            cd ..
            mv $ARCHIVE"2" $ARCHIVE
        fi
        cd $STARTDIR
    fi
else
    'tar' $NEW_ARGS
fi

6EA3 F3F3 B908 2632 A9CB E931 D53A 0445 B47A 0DAB
Great things come in tar.xz packages.

Offline

#1264 2010-08-29 10:12:30

archman-cro
Member
From: Croatia
Registered: 2010-04-04
Posts: 943
Website

Re: Post your handy self made command line utilities

brisbin33 wrote:

wouldn't it be safer to setup a NOPASSWD entry in soduers for those commands rather than store your pwd in plain text in a script?

Yes, I agree, but somehow I feel I should not "polute" the sudoers file with many NOPASSWD entries which I'd use rarely. For instance, I use NOPASSWD for a hibernate or mounting script, but dunno if it's of any use if I put in a new entry for apps I rarely use.
Btw, I know what you mean about security, and I'm always thinking of it. Anyway, I guess the only vulnerability is keeping the actual passwords in a file, because someone who eventually gets into my files might see it? Or is there something else?

Offline

#1265 2010-08-29 12:52:18

Wintervenom
Member
Registered: 2008-08-20
Posts: 1,011

Re: Post your handy self made command line utilities

archman-cro wrote:

Yes, I agree, but somehow I feel I should not "polute" the sudoers file with many NOPASSWD entries which I'd use rarely.

/etc/sudoers wrote:
root  ALL = (ALL) ALL
wintervenom  ALL = (ALL) ALL
wintervenom  ALL = NOPASSWD: /sbin/shutdown
wintervenom  ALL = NOPASSWD: /sbin/reboot
wintervenom  ALL = NOPASSWD: /usr/sbin/pm-suspend
wintervenom  ALL = NOPASSWD: /usr/sbin/pm-hibernate
wintervenom  ALL = NOPASSWD: /usr/bin/netcfg
wintervenom  ALL = NOPASSWD: /usr/bin/netcfg2

I've been using that forever.  It will not hurt anything, I promise.  tongue

Last edited by Wintervenom (2010-08-29 12:53:18)

Offline

#1266 2010-08-29 14:35:58

vik_k
Member
From: Pune, India
Registered: 2009-07-12
Posts: 227
Website

Re: Post your handy self made command line utilities

just cooked up a script for downloading wallpapers randomly from wallbase.net...

it uses elinks & curl.

usage:
        walls [options]
options:
        -p    purity of wallpapers
        -n    no. of wallpapers
        -r    resolution of wallpapers
        -a    aspect ratio of wallpapers (as decimal)
        -d    directory to save wallpapers
        -h    show this message

example:
        walls -n 50 -p 110
        (will download 50 wallpapers excluding NSFW)

CURRENT SETTINGS:
        No. of Images : 40
        Purity             : 110
        Resolution      : 1920x1080
        Aspect Ratio   : 1.77
        Directory        : /home/vikki/pictures/new

PURITY:
        SFW SKETCHY NSFW
         0/1     0/1       0/1

#!/bin/bash
#
# vik_k
# script to download random wallpapers from wallbase.net
###

message() {
  echo
  echo -e "\e[1;37musage:\e[0m"
  echo "        walls [options]"
  echo -e "\e[1;37moptions\e[0m:"
  echo "        -p    purity of wallpapers"
  echo "        -n    no. of wallpapers"
  echo "        -r    resolution of wallpapers"
  echo "        -a    aspect ratio of wallpapers (as decimal)"
  echo "        -d    directory to save wallpapers"
  echo "        -h    show this message"
  echo
  echo -e "\e[1;37mexample:\e[0m"
  echo "        walls -n 50 -p 110"
  echo "        (will download 50 wallpapers excluding NSFW"
  echo
  echo -e "\e[1;37mCURRENT SETTINGS:\e[0m"
  echo "        No. of Images : $WALL_NO"
  echo "        Purity        : $PURITY"
  echo "        Resolution    : $RES"
  echo "        Aspect Ratio  : $ASPECT"
  echo "        Directory     : $WALL_DIR"
  echo
  echo -e "\e[1;37mPURITY:\e[0m"
  echo "        SFW SKETCHY NSFW"
  echo "        0/1   0/1    0/1"
  echo
  exit
}

download_wallpapers() {
  elinks -dump "http://wallbase.net/random/all/eqeq/$RES/$ASPECT/$PURITY/$WALL_NO" | awk '/\/wallpaper/ {print $2}' |\
    while read url; do
      wget -q "$(curl -s "$url" | awk -F\' '/wallbase2.net/ {print $2}')" -P "$WALL_DIR" &&\
      echo -e "\e[32m-->\e[0m wallpaper-$(basename $url)"
    done
    [ $? -eq 0 ] && echo -e "\n==> $WALL_NO wallpapers of $RES downloaded to $WALL_DIR"
}

# defaults
PURITY="110"
WALL_NO="40"
RES="1920x1080"
ASPECT="1.77"
WALL_DIR="${HOME}/pictures/new"

# main
while getopts ":hp:n:r:d:" flags; do
  case $flags in
    h) message                                                          ; exit      ;;
    p) PURITY="$OPTARG"                                                 ; continue  ;;
    n) WALL_NO="$OPTARG"                                                ; continue  ;;
    r) RES="$OPTARG"                                                    ; continue  ;;
    a) ASPECT="$OPTARG"                                                 ; continue  ;;
    d) WALL_DIR="$OPTARG"                                               ; continue  ;;
    :) echo "--> Error: You're missing an argument somewhere. Exiting." ; exit      ;;
    ?) echo "--> Error: Invalide flag somewhere. Exiting."              ; exit      ;;
  esac
done

download_wallpapers

Last edited by vik_k (2010-08-29 14:42:16)


"First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack." ~ George Carrette

Offline

#1267 2010-08-29 16:56:58

ConnorBehan
Package Maintainer (PM)
From: Long Island NY
Registered: 2007-07-05
Posts: 1,359
Website

Re: Post your handy self made command line utilities

Oh a really quick one! This allows me to kill ping with ^C and not have it take forever. The ping signal handler wastes SECONDS of my time!

#!/bin/bash

trap "sudo killall -s SIGKILL ping" SIGHUP SIGINT SIGTERM

'ping' $@ &

pgrep ping >/dev/null
while [ $? -eq 0 ]; do
    sleep 0.1
    pgrep ping >/dev/null
done

6EA3 F3F3 B908 2632 A9CB E931 D53A 0445 B47A 0DAB
Great things come in tar.xz packages.

Offline

#1268 2010-08-29 16:59:57

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

ConnorBehan wrote:

Oh a really quick one! This allows me to kill ping with ^C and not have it take forever. The ping signal handler wastes SECONDS of my time!

#!/bin/bash

trap "sudo killall -s SIGKILL ping" SIGHUP SIGINT SIGTERM

'ping' $@ &

pgrep ping >/dev/null
while [ $? -eq 0 ]; do
    sleep 0.1
    pgrep ping >/dev/null
done

Maybe you can 'ping -c 3 www.google.com' so that it pings only 3 times and exits :-)

Offline

#1269 2010-08-29 19:54:05

ConnorBehan
Package Maintainer (PM)
From: Long Island NY
Registered: 2007-07-05
Posts: 1,359
Website

Re: Post your handy self made command line utilities

Yup, but typing "-c 3" is work! Plus in rare cases, my connections is so bad that it actually won't ping 3 times.


6EA3 F3F3 B908 2632 A9CB E931 D53A 0445 B47A 0DAB
Great things come in tar.xz packages.

Offline

#1270 2010-08-29 19:55:20

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

ConnorBehan wrote:

Yup, but typing "-c 3" is work! Plus in rare cases, my connections is so bad that it actually won't ping 3 times.

[karol@black ~]$ type pong
pong is aliased to `ping -c 3 www.google.com'

Offline

#1271 2010-08-30 01:16:26

Wintervenom
Member
Registered: 2008-08-20
Posts: 1,011

Re: Post your handy self made command line utilities

Simpler $(for) loops in Bash for single tasks.

iterate () {
  if [ -z "$1" ]; then
    echo 'Iterate what command with which variables for :::?'
    return 1
  fi
  cmd="$1"
  shift
  while [ "$1" ]; do
    ${cmd//:::/$1}
    shift
  done
}

Synchronizes a file or directory between machines, in the same path structure.

synchronize () {
  if [ -z "$1" ]; then
    echo 'Synchronize *to* or *from* what *host*, and which *files*?'
    return 1
  fi
  if [ "$1" != 'from' -a "$1" != 'to' ]; then
    echo "I do not know how to synchronize '$1' a host; only 'to' or 'from.'"
    return 1
  fi
  direction="$1"
  shift
  if [ -z "$1" ]; then
    echo "Synchronize ${direction} what host?'"
    return 1
  fi
  host="$1:"
  shift
  sync='rsync -e ssh -axlz --delete --progress'
  while [ "$1" ]; do
    #Yeah, yeah, I know this part could have been done better.  :P
    case "$1" in
      'songs')
        item="${HOME}/Music"
      ;;
      'visions')
        item="${HOME}/Pictures"
      ;;
      'dreams')
        item="${HOME}/Videos"
      ;;
      'stories')
        item="${HOME}/Documents"
      ;;
      'pleasures')
        item="${HOME}/.Evil"
      ;;
      'aliases')
        item="${HOME}/.config/bash/alias"
      ;;
      'bin'|'binaries')
        item="${HOME}/bin"
      ;;
      'firefox'|'mozilla')
        item="${HOME}/.mozilla"
      ;;
      'chrome'|'chromium')
        item="${HOME}/.config/chromium"
      ;;
      'home')
        for item in $HOME/{Music,Pictures,Videos,Documents,bin,.Evil,.config/bash/alias,.mozilla,.config/chromium}; do
          $sync "${item%/}" ${host}"$(dirname "${item/${HOME/\//\\\/}\//}")"
        done
        break
      ;;
      *)
        item="$1"
      ;;
    esac
    if [ "${direction}" = 'to' ]; then
      $sync "${item%/}" ${host}"$(dirname "${item/${HOME/\//\\\/}\//}")"
    else
      $sync ${host}"${item/${HOME/\//\\\/}\//}" "$(dirname "${item%/}")"
    fi
    shift
  done
}
teach () { synchronize to $*; }
learn () { synchronize from $*; }

An example:

iterate "teach ::: visions songs binaries" succubine cannabalis underscorepipe.net anothermachine.somedomain

Synchronizes these directories on current machine to each of the hosts.

Last edited by Wintervenom (2010-08-30 01:19:31)

Offline

#1272 2010-08-30 01:30:14

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

For synchronizing files/directories check out unison.

Offline

#1273 2010-08-31 19:48:18

TaylanUB
Member
Registered: 2009-09-16
Posts: 150

Re: Post your handy self made command line utilities

Ogion wrote:

In a script when you do command substitution (`somecommand` or $()) and you expect whitespace, then you should set the IFS variable so that it does not include whitespace.

IFS='\t\n'

For a longer explanation see for example here

Ogion

Just use double-quotes!

Changing the IFS is needed quite rarely. In the link you gave, the problem is that the values are stuffed into a variable, so a character that doesn't appear in any of the filenames must be used as the IFS. But in real-world usage, you would just use 'find' in that case anyway.

skanky wrote:

Incidentally, and for the record, it's the "..." that solve the problem. the $(...) is a replacement for `...` but I prefer it as it's more obvious when reading - IIRC there are some subtle differences too, see the bash man page for details. smile

With $() it's much much easier to nest; you need nothing special at all. With identical starting and ending symbols, as it is the case with ``, you usually rely on backslashes for nesting; consequentially you need to escape a literal backslash with a second one, which leads to sneaky errors in your code.

For example, i like to use \\n instead of '\n' (one more keypress!); with backtick syntax, it messes up:

> echo $(printf \\n)

> echo `printf \\n`
n

``Common sense is nothing more than a deposit of prejudices laid down by the mind before you reach eighteen.''
~ Albert Einstein

Offline

#1274 2010-08-31 20:07:06

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

@TaylanUB - that's the one, thanks. smile


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#1275 2010-08-31 20:48:44

Ogion
Member
From: Germany
Registered: 2007-12-11
Posts: 367

Re: Post your handy self made command line utilities

For a longer article on the topic of filenames see here (It's long but imo worth it).
Also, changing the IFS in a script really is not much of a problem in my eyes.

Ogion


(my-dotfiles)
"People willing to trade their freedom for temporary security deserve neither and will lose both." - Benjamin Franklin
"Enlightenment is man's leaving his self-caused immaturity." - Immanuel Kant

Offline

Board footer

Powered by FluxBB