![]() |
|
[Shell] A Comprehensive Guide to Bash - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [Shell] A Comprehensive Guide to Bash (/showthread.php?tid=4583443) |
A Comprehensive Guide to Bash - Tirus - Dec 13, 2014 Comprehensive bash guide
![]() What is bash? Bash (Bourne Again Shell) is a unix shell written by Brian Fox for the GNU project to replace sh (Bourne Shell). It is a command processor that typically runs in a text window, where the user types commands that cause actions. Bash can also read commands from a file, called a script. Like all Unix shells, it supports filename wildcarding, piping, here documents, command substitution, variables and control structures for condition-testing and iteration Your first script Let's start with something that is really easy to understand. Lets create a "hello world" script. PHP Code
![]() Running a bash script So after creating your first ever bash script, let's say you saved the contents of the bash script with the name "firstever.sh". The script should have execute permissions for the correct owners in order to be runnable. When setting permissions, check that you really obtained the permissions that you want. When this is done, the script can run like any other command. PHP Code Now that we have gaven our script the permission to run like any other command, we can execute our first bash script! To do this, we will simply type firstever.sh in our terminal. It should look something like this PHP Code This is the most common way to execute a script. It is preferred to execute the script like this in a subshell. The variables, functions and aliases created in this subshell are only known to the particular bash session of that subshell. When that shell exits and the parent regains control, everything is cleaned up and all changes to the state of the shell made by the script, are forgotten. ![]() Variables You can use variables as in any programming languages. There are no data types. A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it. PHP Code Line 2 creates a variable called BH and assigns the string "Hello World!" to it. Then the VALUE of this variable is retrieved by putting the '$' in at the beginning. Please notice (try it!) that if you don't use the '$' sign, the output of the program will be different, and probably not what you want it to be. ![]() Local Variables Local variables can be created by using the keyword local. PHP Code This script here assigns the word "Hello" to "HELLO". We then make a function named "hello" which HELLO = World. Once we echo "$HELLO" it will echo out the variable we made it to, which is world in this case. Now, whenever we execute it again, it'll go back to the first part and execute "Hello" which would print out "Hello world". Fairly basic, right?! Great! ![]() Conditionals Conditionals let you decide whether to perform an action or not, this decision is taken by evaluating an expression. This is useful for if statements, then statements, elseif statements and multiple other statements. You will use conditionals very often in your bash lifetime so get use to them. I will be going over a few conditionals in this section of the guide. If PHP Code Programming conditional statement that, if proved true, performs a function or displays information. Below is a general example of an if statement, not specific to any particular programming language. The code to be executed if the expression within braces is true can be found after the 'then' word and before 'fi' which indicates the end of the conditionally executed code. If then else PHP Code So this little script here says that if the variable foo is equal to "foo" then execute the value as true. If it is not equal to "foo" then return false. If it doesn't return either, do not return anything to the user as this may be a glitch in your code or an error. ![]() Functions Bash has functions, though in a somewhat limited implementation. A function is a subroutine, a code block that implements a set of operations, a "black box" that performs a specified task. Wherever there is repetitive code, when a task repeats with only slight variations in procedure, then consider using a function. As in almost any programming language, you can use functions to group pieces of code in a more logical way or practice the divine art of recursion. Declaring a function is just a matter of writing function my_func { my_code }. Calling a function is just like calling another program, you just write its name. Here is a little sample of a function, below the code I will explain what the code does. PHP Code This code sets the function quit set as "Exit" which would shut down the script upon the line of code being read by your system. The function hello will echo out "Hello". Now, once we call these functions after declaring them, we will have it say our hello function which is equal to "Hello!" and then after that, we go to our quit function which will exit the script upon the function being called, basic right? ![]() User Interfaces(UIs) Graphical user interfaces (GUI) accept input via devices such as a computer keyboard and mouse and provide articulated graphical output on the computer monitor. You can find these very useful in bash and so do I. So in this step, as in the other steps, I will show you what the code looks like and further explain what the code does. Sounds good? Great. PHP Code This code is very basic and is similar to the if statements that we were doing very earlier. So the options are either "HELLO" or "QUIT". This code says if the opt(option) in our variable OPTIONS is "quit" then we will execute the echo "done" and then "exit" which would exit our if statement so the code doesn't carry on to our elif statement. Now, in our elif statement, if it is "HELLO" then it will execute Hello world. If it isn't either of them, the screen will clear. Command Line(CL) PHP Code What this script does should be clear to you. The expression in the first conditional tests if the program has received an argument ($1) and quits if it didn't, showing the user a little usage message. The rest of the script should be clear at this point. If you understand this, then we are going into the right direction regarding bash. ![]() User Input In many occasions you may want to prompt the user for some input, and there are several ways to achive this. This is one of those ways: PHP Code So this will as for a user input by saying "Please enter your name". Upon a users input, the input will go into the $NAME variable and then once it is read it will echo out the variable after the word "Hi". So it would look something like "Hi Tirus!" PHP Code With select you don't need to sanitize the input... it prompts you with your choices, and you type a number corresponding to the choice you want. Select also loops automatically... there's no need for a 'while true' loop to retry if they give invalid input. So to explain this code in my own words, it asks you if you wish to install a program. We then set an option for either "y/n == "Yes", "No". If the case is "y" or "Yes", it will make install; break;;. If the case is "No" it will exit the script(Not install the program that you wish to do. Once it runs through those options, if neither is enter Y/N(Yes, No) it will execute "done" which will close the script and "not install the program." * - Tirus - Dec 13, 2014 ![]() Tables PHP Code To explain what these are I will go in explanation of what each of these tables do. (1) s2 matches s4 (2) s3 does not match s5 (3)_TO-DO_ (4)_TO-DO_ (5) s1 is not null (contains one or more characters) (6) s1 is null C programmer's should simple map the operator to its corresponding parenthesis. This is basic mathematics and if you wish to do any type of bash or any other programming/coding, you must know at-least 7th grade level math to an extent. ![]() Commands Some of these command's almost contain complete programming languages. From those commands only the basics will be explained. For a more detailed description, have a closer look at the man pages of each command. Which you can do by executing man (command).
sed or commonly known as stream editor is a non-interactive editor. Instead of altering a file by moving the cursor on the screen, you use a script of editing instructions to sed, plus the name of the file to edit PHP Code Sed replaces the string 'to_be_replaced' with the string 'replaced' and reads from the /etc/tutfile. The result will be sent to stdout (normally the console) but you can also add '> capture' to the end of the line above so that sed sends the output to the file 'capture'. awk or manipulation of datafiles. AWK scans for a pattern, and for every matching pattern a action will be performed. So lets show you how this command works, it's quite basic. I'm going to create a file named "tutorial" I've created a dummy file containing the following lines: "test123 test tteesstt" PHP Code The result of the file will print out PHP Code In your command line. The pattern AWK looks for is 'test' and the action it performs when it found a line in the file /tmp/dummy with the string 'test' is 'print'. The command grep will print lines matching a search pattern. $grep "look for this" /var/log/messages -c this will search for the text "look for this" in our log folder of messages. This is very basic and a very easy command to use. Although there is not much to it, it can really be useful if you are search for certain texts in your messages folder of logs. wc will counts lines, words and bytes which is an addition to the command grep. I find this one more useful than grep because it can search bytes as-well. Wc doesn't care about the parameter order. Wc always prints them in a standard order. PHP Code sort is a command that will sort lines of text files. Let's say we created a file with the following contents PHP Code As we know, this isn't alphabetically correct. We want it to be alphabetically correct, so to do so, we're going to use the sort command which will alphabetically arrange it correctly. If we execute sort /tmp/tut it will alphabetically arrange it from "b, a, c" to PHP Code ![]() Misc So in this part, I will show you how to find bash. you always use #!/bin/bash .. you might was to give an example of how to find where bash is located in. Here are a few commands you can use to find bash. PHP Code The first one is preferred, but not all machines have locate on them. The second one will work from the root dir will work, usually * - Tirus - Dec 13, 2014 Thank you for taking your time to read over my bash comprehensive guide. I took an incredible amount of time in this tutorial and would love to get some positive feed-back regarding it. If you have absolutely any questions or concerns regarding bash or this tutorial or a matter of fact, anything GNU/Linux related, feel free to contact me via PM and we can fuhrer discuss your problem/question. * - Otis - Dec 13, 2014 Amazing tutorial Tirus. You never failed me with your tutorials. * - Tirus - Dec 13, 2014 Thank you very much .Astro, I plan on being of assistance in the GNU/Linux section for quite some time. * - Loki123 - Dec 13, 2014 Great work Tirus! If you wouldn't have done it I would probably have finished in the next weeks. Not in less than 24 hours. Amazing work! P.S Wrong section ;* * - Tirus - Dec 13, 2014 (Dec 13, 2014 05:58 PM)Loki123 Wrote: Great work Tirus! I have a lot of time on my hands, I did it all night long till 5 AM and then did it all day today till 8 PM. * - Orchid - Dec 13, 2014 Woah this is a very creative guide, thanks Tirus. * - Tirus - Dec 13, 2014 My pleasure, thank you for replying and giving me feed-back, Orchid. I appreciate it. * - White Light - Dec 14, 2014 Wow, very nice guide. One thing I noticed, you said "fuhrer" instead of further. * - 'Palladium - Dec 14, 2014 Tirus, If you rushed this tutorial you must've put little effort into this, Look at Whitelight's guide on Batch, It took him weeks, And it's much more longer. But that's just my opinion. * - Aura 2.0 - Dec 14, 2014 Great tutorial Tirus. (Dec 14, 2014 06:22 AM)HacksBro Wrote: And it's much more longer. Quality, not quantity. * - Tirus - Dec 14, 2014 (Dec 14, 2014 06:22 AM)HacksBro Wrote: Tirus, If you rushed this tutorial you must've put little effort into this, Look at Whitelight's guide on Batch, It took him weeks, And it's much more longer. But that's just my opinion. Quality over quantity. Just because I make a few grammatical errors doesn't mean I left something out. * - WOLGA - Dec 14, 2014 Great post OP, we need more people like you in this section. * - b00st3d - Dec 14, 2014 (Dec 14, 2014 06:22 AM)HacksBro Wrote: Tirus, If you rushed this tutorial you must've put little effort into this, Look at Whitelight's guide on Batch, It took him weeks, And it's much more longer. But that's just my opinion. Did you read this or did you just regurgitate a line to increase post count? This is a good beginners guide on BASH (Bourne Again SHell) This is Linux not M$. Just because he misspelled a word doesn't mean effort wasn't put into it. |