Scripting

From LinuxPadawan Wiki
Revision as of 00:26, 23 September 2016 by Wxl (Talk | contribs) (Protected "Scripting": Staff requested lockdown: "standard" lockdown-- only masters can edit ([Edit=Allow only autoconfirmed users] (indefinite) [Move=Allow only administrators] (indefinite)))

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Shell scripting. Using your terminal emulator to code little "scripts" that string together different *nix command line utilities to perform tasks. Most often used for automation, so it sees a lot of use in the server world.

Terminal emulators

Terminal emulators or often just "terminals" are programs that allow you to access the command line. There are whole hoardes of them out there. I'm not about to offer a comparison, but suffice it to say, your computer has one. Often times you can get to it by running x-terminal-emulator.

Shells

Your default shell is defined in the variable $SHELL and is most often /bin/bash. You can think of these as an interpreter. It interprets input and acts upon it immediately rather than compiling it into machine code. There are also a plethora of shells out there and each has their own pros and cons but bash's popularity is a good reason to use it.

Opening up the terminal

Usually you're faced with little more than a $. This implies you are a non-root user so you can't do some systemwide tasks. If you have a # instead, be careful, because you can do anything you want. Usually to get to a root prompt (#) sudo or su is usually entered and a password is provided.

First program

A traditional way of demonstrating syntax is getting the language to print a particular string. You can make a new file using the editor of your choosing. Let's call it firstprogram.sh and save it to your $HOME, which bash syntax expands from ~. Thus the full path to your program is ~/firstprogram.sh. With the exception of the #! on line one, there is no need to type in the # comments, but when you are writing a script it's always handy to have some comments in for when you re-visit 12 months later!

#!/usr/bin/env bash
# ↑ specifies the interpreter
message="Hello, World!" #creates a string variable
echo "$message" #prints the variable

Unfortunately, you can't run it yet. It's currently just a text file. You can make it executable, though. Surely your file manager can let you do this, but since we've got the terminal open we can do this and run it. You can do this as the prompt ($):

chmod +x ~/firstprogram.sh #makes the file executable
~/firstprogram.sh #runs the program

Learn more

On a related note

If you're comfortable here, you might want to move past scripts, you might try programming!