LinuxQuestions.org
Go Job Hunting at the LQ Job Marketplace
Go Back   LinuxQuestions.org > Blogs > rainbowsally
User Name
Password

Notices

Rate this Entry

KDE Utils: new.symlink, launch, edit, browse, tofile

Posted 01-16-2012 at 01:43 PM by rainbowsally
Updated 01-16-2012 at 01:58 PM by rainbowsally

[Recommended: Kate (Advanced Text Editor).]

In my setup I have HOME/bin with a subdirectory named src where I put my private stockpile of micro-programs and where I can uninstall them easily by simply deleting the files or the directories containing them.

Under HOME/bin/src I have the directories named for the apps they contain, in some cases being collections of apps with additional subdirectories.

In order to put the apps in the path all that is necessary is to symlink the executable in my HOME/bin folder.

You may do this any way you like, but that is my preference and it should pretty much work on any KDE system around, though you may have to logout and back in to set the bin folder in your path (e.g., kubuntu.)

This MIGHT require adding your bin folder to your path as well. (This should be dealt with in the (dot).profile file in kubuntu, but I'm not sure it works right.)

In general (assuming bash is your shell), the following can be added to your (dot).bashrc file to set the path.

Code:
PATH=.:~/bin:$PATH
That adds dot to your path first, which will allow you to run apps in the current directory without the usual dot-slash prefix and it also adds the HOME/bin folder, which are then scanned in a first-to-last order of preference.

Also works for WindowMaker, LXDE, Gnome, and so forth, but for our purposes here we assume that KDE is at least accessible, even if it's not the current desktop manager.

------------------------------------------------
File: new.symlink (executable)
Path: HOME/bin/src/misc
Purpose: easily create a symlink with simple syntax and usage note.

Code:
#!/bin/sh
#new.symlink <FileInCurrentDir> <NewLinkLocation>

if [ $# != 2 ];then
    echo "Usage: new.symlink <FileInCurrentDir> <NewLinkLocation>"
    exit
fi

file="$PWD/$1"
dir="$2"

(cd $dir && ln -sf $file .)
[There may be several apps with the name "new"(dot)<func> that create other files or sets of files that we can look up easily as '~/bi /new.*', so let's go with the dot in the name here.]

Place the file where it will be when it runs and then cd into that folder and link it into your ~/bin folder, using the file itself to generate the link.

Type
Code:
new.symlink new.symlink ~/bin
Note that with dot in your path you do not need to prefix the first name (the command) with "./".

Now it will run (immediately) since it's in your path.

Type 'which new.symlink' to verify. You should see the full path to the symlink in your ~/bin folder.


------------------------------------------------
File: launch (executable)
Path: HOME/bin/src/misc
Purpose: Execute programs noiselessly returning control to the terminal immediately.

Code:
#!/bin/sh
nohup $@ > /dev/null 2>&1 &
exit 0
In the folder containing the file type 'new.symlink launch ~/bin' to install.

Remove the symlink and the file to uninstall. NO SUPERUSER NEEDED. None wanted for these apps.

------------------------------------------------
File: edit (executable)
Path: HOME/bin/src/misc
Purpose: Supercede that SCREWY vim 'edit' app with one that can go to exact lines.

This can take "grep -in <text> <path>" output to go to the exact line in a file where the text is found.

Code:
#!/bin/sh

args=`echo $@ | sed 's|[:]| --line |; s|[:].*| |g;'`
launch "kate -n $args" ### we'll activate 'launch' later
Install and uninstall as per the 'launch' utility above.

When installed type 'edit ~/bin/edit' and verify. This will show the source code for the app. And now the default 'edit' will be superceded by a nicer gui version that can go to exact line numbers.

Try this:
Code:
grep -in fileincurrentdir ~/bin/*
Highlight a chunk of, or even a whole line and copy/past behind the command 'edit', like so:

Code:
edit <pasted text>
Hit ENTER.

You should end up with the cursor on the exact line containing the text. (Not perfect, but nearly always works.)

------------------------------------------------
File: browse (executable)
Path: HOME/bin/src/browse (folder name same as executable name within)
Purpose: Use a KDE gui app to browse files or directories

I put this in a separate directory because we MIGHT want to include a config file for changing the app that we use. For now let's hard-code it (no config).

Code:
#!/bin/sh

BROWSER=konqueror

###############################################################
# read url and if first char is @, read the file instead of url

url="$1"
shift

has_splat()
{
    local tmp=`echo "$url" | sed "/@/! D"`
    if [ "$tmp" = "" ];then
        return 1; #err=no
    else
        return 0; #ok=yes
    fi
}


if has_splat ;then
    # check if first arg is @ alone
    if [ "$url" = "@" ];then
        url=$(<"$1")
        shift
    else # splat is prefixed to url
        url=`echo "$url" | sed "s/^@//"`
        url=$(<$url)
        shift
    fi

fi # has_splat


# compose a command line from url and other args, removing trailing
# spaces if any, so konqueror and other apps don't choke on a bum
# url.  That is a space at the end CAN be part of a valie url.

cmdln=`echo "$url $@" | sed 's/ *$//'`

# fork a system call (returns immediatly after creating new proc)
# and suppress error messages which would otherwise show in the 
# console.  (They could go directly to a log file, but stderr is
# the default for the console and the errors are usually non-fatal
# if they are anything more than warnings in the first place.)

launch "$BROWSER '$cmdln'"
This could probably use a bit of revision, it's an ancient version, but roll with it for now and later we'll see how we could have included a config file to set the browser easily enough without tampering with the executable at all.

Install and uninstall as per above.

To test it, type "browse ~/bin"

Also try "browse ~/bin/browse" and see what happens.

[In konqueror it will prompt you for whether or not to execute it. (Using openSUSE 11.4). No guarantees what other filemanagers or other versions of kde will do. Check and see.]

If you want to you can set your environment to use these apps instead of the crazy defaults, but be aware that as superuser, unless these apps are in root's path the defaults will still run instead of the replacements.

If you prefer the crazy defaults, however, uninstallation is even easier than installation. Just remove the file first and then the broken and easily visible symlink in your ~/bin folder.

Coming Up! A C/C++ program to replace "more" with a gui-based text viewer that allows you to work in the terminal as you view docs or for just about any text produced by linux commandline programs.

[Continued in comment below.]
Posted in Uncategorized
Views 3772 Comments 1
« Prev     Main     Next »
Total Comments 1

Comments

  1. Old Comment
    ---------------------------------------
    File: tofile (compiled)
    Path: HOME/bin/src/tofile-2.0
    Purpose: A way to capture and view output from linux commands (instead of 'more')
    Compile: 'gcc tofile.cpp -o tofile'
    Link: n/a

    [This is a C/C++ program. You may want it as a bash script but bash is so difficult to figure at times that the C was a lot more sensible, at least for me.]

    Install and uninstall as above.

    This (as is edit) are dependent on kate. Kwrite won't work as well for the edit utility (e.g., line number parsing last time I checked) but if you want to you can easily modify this to your own liking even if you don't know a lot of (read "any") C/C++, but I'll let you experiment with the code on your own.

    If you do want to experiment, find 'edit' in the main file below. That's where you can modify the program used to view the document. But change the version number to your own just for kicks. ;-)

    Here are the sources included in the main file.

    File: version.h
    Code:
    // rewrote in C/C++ to give more control over how strings are interpreted
    #define VERSION "2.0"
    File: usage.str
    Code:
    /* usage_str.txt converted with txt2cstr */
    const char* usage_str =
        "\n"
        "Usage: tofile <command> [args]\n"
        "\n"
        "  Sends output of command and args to a file and opens it\n"
        "  in an editor named 'edit', expected to be found in the\n"
        "  user's current PATH.\n"
        "\n"
        "  The following switches may replace <command>\n"
        "\n"
        "    --help            print this message\n"
        "    -v | --version    print version info\n"
        "\n"
        ;
    And here's the main file.

    File: tofile.cpp
    Code:
    // tofile - sends commandline results to file and opens in an editor
    
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h> // getenv()
    #include "usage.str"
    #include "version.h"
    
    #define streq(a, b) (strcmp(a, b) == 0)
    
    void dbg(){}
    
    int do_pipe(const char* filename, char* cmdline);
    int usage(int err);
    int print_version(int err);
    
    int main(int argc, char** argv)
    {
      dbg();
      
      int err = 0;
      
      char cmdline[256];
      char* p = cmdline;
      
      char filename[256];
      sprintf(filename, "%s/tofile.tmp", getenv("HOME"));
      // usage notes
      if(argc < 2)
        return usage(1);
      
      if(streq(argv[1], "--help"))
         return usage(0);
      
      if(streq(argv[1], "-v") || streq(argv[1], "--version"))
        return print_version(0);
    
      if(argc > 16)
      {
        fprintf(stderr, "Too many args. Did you use a splat in an unquoted args list?\n");
        return 1;
      }
      
      // reassemble commandline
      for(int i = 1; i < argc; i++)
        p += sprintf(p, "%s ", argv[i]);
      
      p[-1] = 0;
      
      // pipe the commandline to ~/tofile.tmp
      err = do_pipe(filename, cmdline);
      if(err)
      {
        fprintf(stderr, "\n  Error reading piped command\n\n");
        return 1;
      }
      
      // try some other editors with the output file.  I prefer 'edit'. -rs
      sprintf(cmdline, "edit %s/tofile.tmp", getenv("HOME"));
      return system(cmdline);
    }
    
    
    int usage(int errcode)
    {
      printf("%s", usage_str);
      return errcode;
    }
    
    int do_pipe(const char* filename, char* cmdline)
    {
      int nbytes;
      char buf[4096];
      FILE* outfile = fopen(filename, "wb");
      if(!outfile)
        return 1;
      
      FILE* infile = popen(cmdline, "r");
      if(!infile)
        return 1;
      
      while(!feof(infile))
      {
        *buf = 0;
        nbytes = fread(buf, 1, 4096, infile);
        fwrite(buf, 1, nbytes, outfile);
      }
      fflush(outfile);
      fclose(infile);
      fclose(outfile);
      return 0;
    }
    
    int print_version(int errcode)
    {
      printf("%s\n", VERSION);
      return errcode;
    }
    To test try this:

    Code:
    tofile grep "a" "~/bin/*"
    That will find all occurances of the letter a in the utilities created so far.

    Try it without the quotes around the splatted argument and see what happens.

    For something a bit more useful, try this.

    Code:
    tofile cat --help
    Other helps can be viewed the same way and the terminal is immediately free to use even while the help file is open.

    We'll look at a prettier help viewer in a bit but this is a good example of how we can customize our systems to get the best of linux and kde, working together to produce some common sense tools that do more and/or do it better than either one did before.
    Posted 01-16-2012 at 01:51 PM by rainbowsally rainbowsally is offline
 

  



All times are GMT -5. The time now is 11:50 PM.

Main Menu
Advertisement

My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration