Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Preface: I love bash and have no intention of starting any sort of argument or holy-war, and hopefully this is not an extremely naive question.

This question is somewhat related to this post on superuser, but I don't think the OP really knew what he was asking for. I use bash on FreeBSD, linux, OS X, and cygwin on Windows. I've also had extensive experience recently with PowerShell on Windows.

Is there a shell for *nix, already available or in the works, that is compatible with bash but adds a layer of object-oriented scripting into the mix? The only thing I know of that comes close is the python console, but as far as I can tell it doesn't provide access to the standard shell environment. For example, I can't just cd ~ and ls, then chmod +x file inside the python console. I would have to use python to perform those tasks rather than the standard unix binaries, or call the binaries using python code.

Does such a shell exist?

share|improve this question
3  
There's Pash but that's much more Powershell-like than Bash-like. –  ephemient Dec 2 '10 at 21:59
1  
@ephemient maybe you should write an answer for pash... though I know nothing 'bout it, iirc, powershell is an OO shell. –  xenoterracide Dec 4 '10 at 10:10
2  
Hey, you should check out ipython. If you enter an expression that doesn't make sense as python, it will try to map it to a shell command. For example, stuff like cd ~ followed by ls works as in Bash. You can also assign output to Python variables (lists of lines . . sort of) with commands like listing = !ls. –  intuited Dec 5 '10 at 3:42
    
@intuited: awesome, I'll check it out –  Robert S Ciaccio Dec 5 '10 at 3:45
1  
@intuited: iPython has been pretty good for the stuff I want to do, thanks! –  Robert S Ciaccio Jan 7 '11 at 19:23

9 Answers 9

up vote 23 down vote accepted

I can think of three desirable features in a shell:

  • Interactive usability: common commands should be quick to type; completion; ...
  • Programming: data structures; concurrency (jobs, pipe, ...); ...
  • System access: working with files, processes, windows, databases, system configuration, ...

Unix shells tend to concentrate on the interactive aspect and subcontract most of the system access and some of the programming to external tools, such as:

  • bc for simple math
  • openssl for cryptography
  • sed, awk and others for text processing
  • nc for basic TCP/IP networking
  • ftp for FTP
  • mail, Mail, mailx, etc. for basic e-mail
  • cron for scheduled tasks
  • wmctrl for basic X window manipulation
  • dcop for KDE ≤3.x libraries
  • dbus tools (dbus-* or qdbus) for various system information and configuration tasks (including modern desktop environments such as KDE ≥4)

Many, many things can be done by invoking a command with the right arguments or piped input. This is a very powerful approach — better have one tool per task that does it well, than a single program that does everything but badly — but it does have its limitations.

A major limitation of unix shells, and I suspect this is what you're after with your “object-oriented scripting” requirement, is that they are not good at retaining information from one command to the next, or combining commands in ways fancier than a pipeline. In particular, inter-program communication is text-based, so applications can only be combined if they serialize their data in a compatible way. This is both a blessing and a curse: the everything-is-text approach makes it easy to accomplish simple tasks quickly, but raises the barrier for more complex tasks.

Interactive usability also runs rather against program maintainability. Interactive programs should be short, require little quoting, not bother you with variable declarations or typing, etc. Maintainable programs should be readable (so not have many abbreviations), should be readable (so you don't have to wonder whether a bare word is a string, a function name, a variable name, etc.), should have consistency checks such as variable declarations and typing, etc.

In summary, a shell is a difficult compromise to reach. Ok, this ends the rant section, on to the examples.


  • The Perl Shell (psh) “combines the interactive nature of a Unix shell with the power of Perl”. Simple commands (even pipelines) can be entered in shell syntax; everything else is Perl. The project hasn't been in development for a long time. It's usable, but hasn't reached the point where I'd consider using it over pure Perl (for scripting) or pure shell (interactively or for scripting).

  • IPython is an improved interactive Python console, particularly targetted at numerical and parallel computing. This is a relatively young project.

  • irb (interactive ruby) is the Ruby equivalent of the Python console.

  • scsh is a scheme implementation (i.e. a decent programming language) with the kind of system bindings traditionally found in unix shells (strings, processes, files). It doesn't aim to be usable as an interactive shell however.

  • zsh is an improved interactive shell. Its strong point is interactivity (command line edition, completion, common tasks accomplished with terse but cryptic syntax). Its programming features aren't that great (on par with ksh), but it comes with a number of libraries for terminal control, regexps, networking, etc.

  • fish is a clean start at a unix-style shell. It doesn't have better programming or system access features, but has room to evolve them one day (in the form of a new, more powerful set of control structures).


Addendum: another part of the unix toolbox is treating many things as files:

  • Most hardware devices are accessible as files.
  • Under Linux, /sys provides more hardware and system control.
  • On many unix variants, process control can be done through the /proc filesystem.
  • FUSE makes it easy to write new filesystems. There are already existing filesystems for converting file formats on the fly, accessing files over various network protocols, looking inside archives, etc.

Maybe the future of unix shells is not better system access through commands (and better control structures to combine commands) but better system access through filesystems (which combine somewhat differently — I don't think we've worked out what the key idioms (like the shell pipe) are yet).

share|improve this answer
    
You hit the nail on the head right after you say "I suspect this is what you're after". The main reason I'm asking this question is that I love having the power of unix tools, but the text-based interaction between programs definitely 'raises a barrier for more complex tasks'. I've spent enough of my programming days writing text parsers :) I think this is a very well thought out answer. It gets to the heart of the issue and the complexity of the subject. I wish I could upvote it twice :P –  Robert S Ciaccio Dec 2 '10 at 23:03
    
qdbus isn't KDE-specific; it can talk to any dbus service, with a much nicer command-line interface than dbus-send. –  ephemient Dec 2 '10 at 23:04
1  
+1 for ipython, though I have no idea what the OP wants to do. –  Falmarri Dec 2 '10 at 23:19
    
@ephemient: noted, thanks. –  Gilles Dec 2 '10 at 23:20
    
@falmarri: this is more of a general question, I don't want to get bogged in specific examples. –  Robert S Ciaccio Dec 2 '10 at 23:32

There're Rush which uses ruby and Psh which is based on perl.

share|improve this answer

IPython is surprisingly convenient to use.

Standard shell features: job control, readline editing and history, aliases, cat ls cd and pwd, pager integration, running any system command by prefixing it with a ! or enabling %rehashx, command output assignable to a python variable, python values available as shell variables.

Python-specific: reusing results from the last commands, quick access to documentation and source, module reloading, debugger. Some cluster support if you're into that.

That said, running complex pipes isn't done in Python; you'll be using the posix shell as well, just with some glue to pass values to and fro.

share|improve this answer

ksh93t+ is introducing some OO concepts while retaining the bourne/posix shell syntax: http://blog.fpmurphy.com/2010/05/ksh93-using-types-to-create-object-orientated-scripts.html

share|improve this answer

oo-style library for bash 4. Written in bash. Source and use.

http://sourceforge.net/projects/oobash/files/

Still a very young fun project...

share|improve this answer

If someone wants only the basics of object-oriented programming (properties and methods) than a really simple framework would do the trick.

Let's say you want to display the text "Hello World" using objects. First you create an object class which has a property for the text to be displayed and has some methods to set this text and display it. To show how multiple instances of a class can work together I have added two methods for displaying the text : one with NewLine at the end and one without that.

Class definition file : EchoClass.class

# Define properties
<<InstanceName>>_EchoString="Default text for <<InstanceName>>"

# Define methods
function <<InstanceName>>_SetEchoString()
{
  <<InstanceName>>_EchoString=$1
}

function <<InstanceName>>_Echo()
{
  # The -ne parameter tells echo not to add a NewLine at the end (No Enter)
  echo -ne "$<<InstanceName>>_EchoString"
}

function <<InstanceName>>_EchoNL()
{
  echo "$<<InstanceName>>_EchoString"
}

Please note the word "< < InstanceName > >". This will be replaced later to create multiple instances of a class object. Before you can use an instance of an object you need a function which actually creates it. To keep things simple it will be a separate script called : ObjectFramework.lib

# 1st parameter : object instance name
# 2nd parameter : object instance class

function CreateObject()
{
  local InstanceName=$1
  local ObjectClass=$2
  # We will replace all occurences of the text "<<InstanceName>>" in the class file 
  # to the value of the InstanceName variable and store it in a temporary file
  local SedString='s/<<InstanceName>>/'$InstanceName'/g '$ObjectClass'.class'
  local TmpFile=$ObjectClass'_'$InstanceName'.tmp'
  sed $SedString > $TmpFile

  # The file will contain code which defines variables (properties) and functions (methods)
  # with the name we gave to our object instance via the 1st parameter of this function
  # ... we run this code so the variables and functions are actually defined in runtime
  source "$TmpFile"

  # Than remove the temp file as we don't need it any more
  rm "$TmpFile"
}

So now we have a class definition file and a CreateObject function which creates a copy of this file with the text "< < InstanceName > >" replaced to whatever name we want.

Let's use our new object in a script called : HelloWorld.sh (please note that HelloWorld.sh should be executable. The other two files don't need to)

# Define the CreateObject function via the lib file we created
source ObjectFramework.lib

# Create two instances of the EchoClass class
CreateObject MyHello EchoClass
CreateObject MyWorld EchoClass

# Call the SetEchoString method of the two objects. In reality these are 
# just two identical functions named differently and setting different
# variables (remember the <<InstanceName>>_EchoString variable?)
MyHello_SetEchoString "Hello "
MyWorld_SetEchoString "World"

# Finally we call the Echo and EchoNL (NewLine) methods
MyHello_Echo
MyWorld_EchoNL

By running the HelloWorld.sh script it displays the text "Hello World" (and adds a NewLine). Nobody will be impressed much by this result, however we will know this is not that simple as it looks like :)

Happy coding!

share|improve this answer

You don't need much bash code to implement classes or objects in bash.

Say, 100 lines.

Bash has associative arrays that can be used to implement a simple Object system with inheritance, methods and properties.

So, you would might define a class like this:

class Queue N=10 add=q_add remove=q_remove

Creating an instance of this Queue might be done like this:

class Q:Queue N=100

or

inst Q:Queue N=100

Since classes are implemented with an array, class and inst are really synonyms - sort of like in javascript.

Adding items into this queue could be done like this:

$Q add 1 2 aaa bbb "a string"

Removing items into a variable X might be done like this:

$Q remove X

And dumping structure of an object could be done like this:

$Q dump

Which would return something like this:

Q {
      parent=Queue {
                     parent=ROOT {
                                   this=ROOT
                                   0=dispatch ROOT
                                 }
                     class=Queue
                     N=10
                     add=q_add
                     remove=q_remove
                     0=dispatch Queue
                   }
      class=Q
      N=4
      add=q_add
      remove=q_remove
      0=dispatch Q
      1=
      2=ccc ddd
      3=
      4=
    }

Classes are created using a class function like this:

class(){
    local _name="$1:"                            # append a : to handle case of class with no parent
    printf "$FUNCNAME: %s\n" $_name
    local _this _parent _p _key _val _members
    _this=${_name%%:*}                           # get class name
    _parent=${_name#*:}                          # get parent class name
    _parent=${_parent/:/}                        # remove handy :
    declare -g -A $_this                         # make class storage
    [[ -n $_parent ]] && {                       # copy parent class members into this class
        eval _members=\"\${!$_parent[*]}\"       # get indices of members
        for _key in $_members; do                # inherit members from parent
            eval _val=\"\${$_parent[$_key]}\"    # get parent value
            eval $_this[$_key]=\"$_val\"         # set this member
        done
    }
    shift 1

    # overwrite with specific values for this object
    ROOT_set $_this "$@" "0=dispatch $_this" "parent=${_parent:-ROOT}" "class=$_this"
}

NOTE: When defining a new class or instance, you can override any member value or function.

Bash associative arrays have a quirk that makes this work neatly: $Q[0]} is identical to $Q. This means that we can use array name to call a method dispatch function:

dispatch(){
    local _this=$1 _method=$2 _fn
    shift 2
    _fn="$_this[$_method]"                       # reference to method name
    ${!_fn} $_this "$@"
}

A down side is that I can not use [0] for data so my queues (in this case) start from index=1. Alternatively I could have used associative indices like "q+0".

To get and set members you might do something like this:

# basic set and get for key-value members
ROOT_set(){                                       # $QOBJ set key=value
    local _this=$1 _exp _key _val
    shift
    for _exp in "$@"; do
        _key=${_exp%%=*}
        _val="${_exp#*=}"
        eval $_this[$_key]=\"$_val\"
    done
}

ROOT_get(){                                       # $QOBJ get var=key
    local _this=$1 _exp _var _key
    shift
    for _exp in "$@"; do
        _var=${_exp%%=*}
        _key=${_exp#*=}
        eval $_var=\"\${$_this[$_key]}\"
    done
}

And to dump an object structure, I made this:

NOTE: This is not required for OOP in bash, but it is nice to see how objects are made.

# dump any object
obj_dump(){                                      # obj_dump <object/class name>
    local _this=$1 _j _val _key; local -i _tab=${2:-(${#_this}+2)}  # add 2 for " {"
    _tab+=2                                      # hanging indent from {
    printf "%s {\n" $_this
    eval "_key=\"\${!$_this[*]}\""
    for _j in $_key; do                          # print all members
        eval "_val=\"\${$_this[\$_j]}\""
        case $_j in
            # special treatment for parent
            parent) printf "%*s%s=" $_tab "" $_j; ${!_val} dump $(( _tab+${#_j}+${#_val}+2 ));;
                 *) printf "%*s%s=%s\n" $_tab "" $_j "$_val";;
        esac
    done
    (( _tab-=2 ))
    printf "%*s}\n" $_tab ""
    return 0
}

My OOP design has not considered objects within objects - except for inherited class. You could create them separately, or make a special constructor like class(). *obj_dump* would need to be modified to detect internal classes to recursively print them.

Oh! and I manually define a ROOT class to simplify class function:

declare -gA ROOT=(    \
  [this]=ROOT         \
  [0]="dispatch ROOT" \
  [dump]=obj_dump     \
  [set]="ROOT_set"    \
  [get]="ROOT_get"    \
)

With a few queue functions I defined some classes like this:

class Queue          \
    in=0 out=0 N=10  \
    dump=obj_dump    \
    add=q_add        \
    empty=q_empty    \
    full=q_full      \
    peek=q_peek      \
    remove=q_remove

class RoughQueue:Queue     \
    N=100                  \
    shove=q_shove          \
    head_drop=q_head_drop

Created some Queue instances and made them work:

class Q:Queue N=1000
$Q add aaa bbb "ccc ddd"
$Q peek X
$Q remove X
printf "X=%s\n" "$X"
$Q remove X
printf "X=%s\n" "$X"
$Q remove X
printf "X=%s\n" "$X"


class R:RoughQueue N=3
$R shove aa bb cc dd ee ff gg hh ii jj
$R dump
share|improve this answer

Now, with what objects are you dealing in a shell most of the time? It's files/directories, processes and their interaction. So it should like f1.edit or something like currentFile=f1.c ; .edit ; .compile ; .run. Or d1.search(filename='*.c' string='int \*'). Or p1.stop, p1.bg. That's my understanding of an ooshell.

share|improve this answer

jq works quite well as such a sort of object-oriented layer.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.