Creating classes and objects using bash scripting
list in shell script
how to take array input in shell script
bash array
bash associative array
bash dictionary
bash for loop
json in shell script
I'm trying to use bash scripting to make an script act like a phone book, so i tried to create classes and objects but unfortunately i couldn't find a way to do that ! so i'm asking how to create a class using bash scripting??
Bash is a scripting language, that doesn't support OOP, so you can't. Try Python.
The only other thing you could do is have several arrays, but that's messy. Use the index to link them.
Creating array of objects in bash, You could do some trickery with associative arrays (introduced in Bash 4.0) and namerefs (see manual for declare and the first paragraph of Shell Parameters Scripts can be written for all kinds of interpreters — bash, tsch, zsh, or other shells, or for Perl, Python, and so on. You could even omit that line if you wanted to run the script by sourcing it at the shell, but let’s save ourselves some trouble and add it to allow scripts to be run non-interactively.
You can try to do something like this
example.sh
#!/bin/bash # include class header . obj.h . system.h # create class object obj myobject # use object method myobject.sayHello # use object property myobject.fileName = "file1" system.stdout.printString "value is" system.stdout.printValue myobject.fileName
obj.h
obj(){ . <(sed "s/obj/$1/g" obj.class) }
obj.class
# Class named "obj" for bash Object # property obj_properties=() # properties IDs fileName=0 fileSize=1 obj.sayHello(){ echo Hello } obj.property(){ if [ "$2" == "=" ] then obj_properties[$1]=$3 else echo ${obj_properties[$1]} fi } obj.fileName(){ if [ "$1" == "=" ] then obj.property fileName = $2 else obj.property fileName fi }
system.h
. system.class
system.class
system.stdout.printValue(){ echo $($@) } system.stdout.printString(){ echo $@ }
Link for reference: https://github.com/mnorin/bash-scripts/tree/master/objects The point is you can't create objects but you can emulate object-oriented programming in bash
Object-oriented shell for *nix, scsh is a scheme implementation (i.e. a decent programming language) with the kind of system bindings You don't need much bash code to implement classes or objects in bash. Classes are created using a class function like this: class(){ Learn the complete set of linux and bash commands. Learn how to automate things in Linux Learn how to program in Bash Shell and writing professional water tight scripts. Learn an exhaustive details about grep, fgrep, egrep etc and its various use case. Learn and understand exec and shell redirection and various use case.
So I remember checking this question and answer a few years back .. and was thinking.... WHAT!?!?!
Then last week I took a closer look at @Maxims answer and then it became clear..
I have spent the last week and created a bash class transpiler and class loader for class object, with methods and other goodies.. all cause I wanted to create a terminal animation infrastructure:
So while this is just a start I found this to be a SUPER cool and challenging adventure.. I hope my code would help someone else as well!!
BTW: Was tested only on MAC OS so some tweaking might be needed :)
Object Oriented Programming in Bash, First at all create an script in which you will define your class, and give it execution permissions. touch vector.sh chmod +x vector.sh. Then copy It is used to initialize objects of that class type. Add the following constructor to the BankAccount type. Place the following code above the declaration of MakeDeposit: public BankAccount(string name, decimal initialBalance) { this.Owner = name; this.Balance = initialBalance; } Constructors are called when you create an object using new.
Try with BashX: https://github.com/reduardo7/bashx
Example
#!/usr/bin/env bash # ... @Actions.action1() { # \\n Action without arguments set -x pwd @log " Action 1 Multi-Line " ls -la bash } @Actions.action2() { # param1 [param2] \\n Action with arguments\\n\\tdescription second line\\nother line eval "$(@user.options 'new:-n|-N' 'path:-p|--path:true')" set -x @log "'n' or 'N' parameter: ${user_options_new}" @log "'p' or 'path' parameter: ${user_options_path[@]} (${#user_options_path[@]})" local param1="$1" local param2="$2" [[ "$param1" != 'asd' ]] && @throw.invalidParam param1 @log Action 2 @log Param1: $1 @log Param2: $2 } @app.run "$@"
Usage
./myscript action1 ./myscript action2 -n -p /tmp 'my param 1'
Bash declare command – Linux Hint, a variable in longhand. Lastly, it allows you to peek into variables. #!/bin/bash # include class header . obj.h . system.h # create class object obj myobject # use object method myobject.sayHello # use object property myobject.fileName = "file1" system.stdout.printString "value is" system.stdout.printValue myobject.fileName
While there's no true way to create classes in Bash, you can get a little creative. I've found over the years that my preferred way to do this is to create a function that returns a command that can be executed to change state or read properties of the instance. The instance data can be stored in an array.
For example, if you wanted to make a class for binary search trees, you could have this in BinarySearchTree.sh
:
__BINARYSEARCHTREE_INSTANCE_DATA__=() __BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__=() __BINARYSEARCHTREE_INSTANCE_DATA_SIZE__=() BinarySearchTree() { echo "__BinarySearchTree__ $RANDOM " } __BinarySearchTree__() { local id="$1" local code="$2" case "$code" in '.insert' | '[insert]' | "['insert']" | '["insert"]') local value="$3" if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then local length="${__BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]}" local new_node="$length" __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]="$value" length=$((length + 1)) __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]='' length=$((length + 1)) __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]='' local current_node=0 local parent while [ 1 ]; do parent="$current_node" if [ "$value" -lt "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node))"]}" ]; then current_node="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 1))"]}" if [ "$current_node" == '' ]; then __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((parent + 1))"]="$new_node" break fi else current_node="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 2))"]}" if [ "$current_node" == '' ]; then __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((parent + 2))"]="$new_node" break fi fi done __BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]="$((length + 1))" __BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]="$((${__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]} + 1))" else __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0]="$value" __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 1]='' __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 2]='' __BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]=3 __BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]=1 fi;; '.has' | '[has]' | "['has']" | '["has"]') local value="$3" local current_node=0 if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then while [ 1 ]; do local current_value="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node))"]}" if [ "$current_value" == "$value" ]; then return 0 fi if [ "$value" -lt "$current_value" ]; then current_node=${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 1))"]} else current_node=${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 2))"]} fi if [ "$current_node" == '' ]; then return 1 fi done else return 1 fi;; '.size' | '[size]' | "['size']" | '["size"]') if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then echo "${__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]}" else echo 0 fi;; '.empty' | '[empty]' | "['empty']" | '["empty"]') if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then return 1 else return 0 fi;; '.clear' | '[clear]' | "['clear']" | '["clear"]') unset "__BINARYSEARCHTREE_INSTANCE_DATA__[$id, 0]" esac }
And then make objects like this:
source './BinarySearchTree.sh' process() { local tree="$1" $tree.insert 52 $tree.insert -150 $tree.insert 42 if $tree.has 42; then echo 'Has 42!' else echo 'Does not have 42!' fi $tree.clear echo "Size: $($tree.size)" } main() { local tree=$(BinarySearchTree) process "$tree" } main "$#" "$@"
The advantages of this method are that objects can be passed into other functions and there are no external file operations. Even though this may seem impractical, it actually makes Bash quite a nice language to work in since you can modularize your classes.
Array Basics in Shell Scripting, Finally, I created a convenience method for creating a script corresponding to the 1.0 version of my custom image. 1. 2. 3. 4. OzZeroConfImageScript class >> But, it’s just a simple step from the generic custom object to a named dynamic .NET object that I can create, manage, and use in many different contexts. In this post, I’ll use the new class feature of the Windows PowerShell 5.0 preview to create a Keyword class and real Keyword objects.
bash scripts, The aim of Bash Infinity is to maximize readability of bash scripts, minimize the amount of code in bash ( util/type ); type system for object-oriented scripting ( util/class ) If you create your variables using the oo-framework's handle-creating New-Object -ComObject WScript.Shell New-Object -ComObject WScript.Network New-Object -ComObject Scripting.Dictionary New-Object -ComObject Scripting.FileSystemObject Although most of the functionality of these classes is made available in other ways in Windows PowerShell, a few tasks such as shortcut creation are still easier to do using the
niieani/bash-oo-framework: Bash Infinity is a modern , Creating and running a script; 2.2. Script basics Chapter 8: Interactive scripts: making scripts user-friendly, catching user input. You only need one object, for instance a file, to do the operation on. Character ranges and classes in Bash Creating classes can simplify programming tasks that involve specialized data structures or large numbers of functions that interact with special kinds of data. MATLAB classes support function and operator overloading, controlled access to properties and methods, reference and value semantics, and events and listeners.
Bash Guide for Beginners, Using command substitution to generate the case variable; 11-28. can target and operate on whitespace using the POSIX character class [:space:]. as a shared library (DLL) module from a properly compiled object file. There are three steps when creating an object from a class − Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor.
Comments
- You can't;
bash
is not an object-oriented language. - Detailed example here: hipersayanx.blogspot.com/2012/12/…
- @michaelok that is a lot of code for a rather static "class". I think Maxim's answer on here is closer to a class.
- True, though I do see he included a multiple-inheritance (?!) capability so if you take that out, it trims the code down a bit. Thinking about it, why stop there, at OO, how about a "functional" bash, say Idris-like? In all seriousness, this gets back to your original point about Python, and thinking a line from Jurassic Park, even though you can have OO bash (or fp-bash), doesn't mean you should do it - that's what Python is for.
- An actual answer to the question even though it technically doesn't have one, plus 10 for creativity. One must understand OOP is just a concept. If you break it down to binary, nothing is inherently "OOP" anyway. So why not have objects in Shell simply like above.
- Any hack for inheritance?
- I have an idea for an inheritance, will do it later probably
- waiting for the inheritance implementation
- Exactly the point of the last sentence in the answer. You can't create any real classes or objects in bash.