Latest Updates: bash RSS

  • Articles

    5 simple Bash tips

    Stii 10:31 am on March 17, 2009 | Comments: 0 Permalink | Reply
    Tags: bash, command line, , , tips and tricks

    If you work in the command line on Bash a lot you’ll probably find that you often repeat commands. Often you need to run similar commands, but change something like a path, for example. Below are 5 very basic and simple things you should get into the habit of using as they just might make your life simpler. They work wonders for me :)

    1. Search the command history:

    $ ctrl+r
    (reverse-i-search)`ls': ls - l /opt/local/var/db/mysql5
    

    This is by far the handiest tip. On the command line, press the Control button and R. This will activate a reverse interactive search. start typing something that was in the command and it will return the last command with the text in it. If it is not this particular command you were looking for, press Control+R again and it will return the next command. Keep hitting Control+R until you find the command you were looking for and hit enter to run the command. It beats retyping commands or pressing the up arrow until you get the command. :)

    2. Edit the previous command

    $ fc
    

    Running the fc command opens your default system editor (VIM in most cases) and allow you to edit the command. After your changes when you exit VIM your edited command will execute. This is handy if you were running a complex long command but made a mistake and need to edit some things somewhere in the middle of the complex command. Handy if you remember you can do that.

    3. Run the last command of a certain type

    $ !ssh
    ssh -l stii stii.co.za
    

    If you’ve ran a bunch of commands and cannot remember exactly when last you ran a certain command, but you know you want to run the last ssh command, use the !ssh to run the last ssh command you’ve executed. This will save you time again on paging up through your history to find that command.

    4. Run the last command of a certain type, replacing some values

    $ !ssh:s/stii.co.za/afrigator.com
    ssh -l stii afrigator.com
    

    Same as the previous command except it will replace the domain name stii.co.za with the domain afrigator.com. Very, very handy one for running repetitive commands with different arguments. It sure as hell beats finding the command, backspacing the argument you want to change and typing in the correct value!

    5. Swop two characters quickly

    If you have twiddle fingers or cronic dyslexia like some of us, then this one’s a gem. ;) Lets say you typed a command and swapped two characters around:

    $ cd /home/afrigtaor
    

    Instead on moving your cursor to the a, backspacing twice and retyping the a and t in the correct order, all you need to do is to move your cursor to the a and press Control+t and it will swop the t and the a around fixing your typo. Although this one is a bit of a useless one, if you do swap characters often, it might be handy to know of this trick ;)

    These tips are very basic and would probably not be news for most experienced Bash aficionados. I find these very handy and use them often on a daily basis, so maybe it could be handy to someone else. If you have a set of your own favorite tricks, please do let me know as I love learning and improving! Happy Bashing!

    Welcome back! You should subscribe to my RSS feed here.
    You should follow me on Twitter here
    You should follow me on Gatorpeeps here.

    Save Cape Town City Ballet
     
  • Articles

    Using Bash to update Twitter with the current playing track in iTunes

    Stii 5:15 pm on March 2, 2009 | Comments: 5 Permalink | Reply
    Tags: bash, curl, itunes, , osascript, perl,

    Bash can do everything. From curing cancer right up to making you look cool :) I wanted to update Twitter when I listen to something very, very cool like Tom Waits.

    This Bash script gets the info of the current playing track from iTunes using the osascript command (osascript executes AppleScript, so naturally, this is for OSX ;-) ) and tweets it using curl. I had to use Perl to encode the update string since characters like & was not behaving kind! :) Here it is:

    #!/bin/sh
    
    state=`osascript -e \
    'tell application "iTunes" to player state as string'`;
    if [ $state = "playing" ]; then
            artist=`osascript -e \
            'tell application "iTunes" to \
            artist of current track as string'`;
            track=`osascript -e \
            'tell application "iTunes" to \
            name of current track as string'`;
            album=`osascript -e \
           'tell application "iTunes" to \
           album of current track as string'`;
            msg="Listening to $track by $artist from $album";
            curl --basic --user "username:password" \
            --data-ascii "status=`perl -MURI::Escape -e \
            "print uri_escape('$msg');"`" \
    
    http://twitter.com/statuses/update.json
    
    fi
    

    I saved it in a script called tweettune and

    chmod 755 tweettune
    

    to make it executable. If you run the script it will return the update in JSON format.

    It works great. If you are cooler and your Bash is hotter than mine, please send/leave me the code to try!

    PS: remember to replace username:password with your Twitter login credentials.
    PPS: Yes, I know OAuth for Twitter is out. This is not about using OAuth, but updating your Twitter status with the current track playing in iTunes.

    Save Cape Town City Ballet
     
  • Articles

    How to calculate the days between two dates using Python. Quickly.

    Stii 12:56 pm on February 6, 2009 | Comments: 3 Permalink | Reply
    Tags: bash, , ,

    This is one of those pretty useless things, but you never know when you might just have the need for something like this… I have not taken the time to investigate a quicker way using Bash, but my love of Python made me use it without even thinking twice! :)

    I first fired up the interactive Python interpreter by simply typing the command python. Next, I imported the datetime module. Did a simple timedelta between two datetime objects and Jack’s your uncle.

    $ python
    Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
    [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
    Type "help", "copyright", "credits" or "license"
    for more information.
    >>> import datetime
    >>> print (datetime.date(2009, 03, 31) \
    ... - datetime.date(2009, 02, 06)).days
    53
    >>>
    

    Python not only is an excellent programming language, it is also a brilliant general purpose toolbox! Bash/Awk/whatever experts, is there a quicker way maybe? Would love to know.

    Save Cape Town City Ballet
     
  • Articles

    Bash script or command to get a process id

    Stii 7:00 am on January 23, 2009 | Comments: 4 Permalink | Reply
    Tags: bash, , , shell-scripts

    bash logoBash (a.k.a. Bourne Again SHell) is one of the best tools you’ll ever come across on Linux, Unix or OSX. You can do virtually anything with it! It is said that bash even cures cancer! Now, let me make this very, very clear… I’m not an expert. I haven’t written much bash scripts for the past 5 years, so it would be fair to say I’m a n00b. At the very least, I’m not a l33t bash afiçionado.

    I had a specific need. I needed a way to find out if a process was running and to obtain its process id (pid). Well, in all honesty, I didn’t REALLY needed the pid, but thought it could maybe be handy for some, so I included it anyway. In my case, all I wanted to know was whether a process was running and if not, to start it. I digress.

    First what I needed was to find the process I’m looking for:

    #!/bin/bash
    
    pid=`ps -eo pid,args | grep myprocess | \
    grep -v grep | cut -c1-6`
    #do what I need with the pid
    

    What we did here:

    First we get the process with the ps command. the -e option tells it to find processes in the entire environment. Without -e it will return only the processes owned by the user who runs the command. The -o option lets you specify which fields you want. That is exactly what the pid,args are. It is the fields we want, and the only fields we want in this instance.

    Next we pipe the ps command through the grep command. grep extracts all the lines the ps command return that contains the string you specify, in this case “myprocess”.

    Since the grep command will also return the grep process, we need to pipe it to another grep command to remove the grep proccess itself. The -v option tells grep to do an invert match, i.o.w. exclude the line containing the word “grep”. Lets look at an example:

    If we only use:

    $ ps -eo pid,args | grep myprocess
    1234    /path/to/myprocess.sh
    34761  grep myprocess
    

    It returns two lines. We’re not interested in the second line and need to exclude it so the command:

    $ ps -eo pid,args | grep myprocess | grep -v grep
    1234   /path/to/myprocess.sh
    

    grep -v grep excludes the line that contains “grep”. Nifty. Just what we need.

    The next step is to get the pid (process id) piping the results to the cut command. The -c1-6 simply says “cut the characters from the first character up to and including the 6th character”.

    ... cut -c1-6
    

    There you have it! You can now do what you need to with that process id. Crush it, Kill it, Destroy it, whatever tickles your fancy!

    I’d like to know from the real experts, what would be an easier way to do it? More important, what would be a better way to do it? I have to be honest, I didn’t really googled much for an answer since I was busy doing the Afrigator language files and was looking for anything to procrastinate on and this seemed like great fun! My solution might not be very good. For example, it does not allow for more than one process. It assumes that there would always only be one process running. It should be easy enough to allow for more than one process, but I’ll leave that up to you! You would need to split the lines… argh, just figure it out!

    PS: Justin & Lester, next time you give me grief, I will replace the two of you with bash scripts!

    Update:

    Here is a simpler command by Donald Jackson via Twitter utilizing awk:

    $ ps aux | grep processname | grep -v grep | awk '{print $2}'
    

    Thanx @donaldza

    Save Cape Town City Ballet
     

About Me

Software developer at Afrigator.com Love Python, do PHP.
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
esc
cancel