Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shell Scripting 101: The Basics
#1
When you work with Linux systems (or even just *NIX systems in general), shell scripting is a useful skill to have. Just knowing the basics can help you out on a way of automating everything! 

We use shell scripting a lot here - from provisioning new systems to performing maintenance. This is going to be a very basic tutorial just to get you started. I'll post more as I have time and if there's an interest.

Creating a script
First things first, you need a new text file. On Windows, I would recommend using Windows Subsystem for Linux and Visual Studio Code (there are several guides out there on how to integrate them). Avoid using Notepad. While Notepad does edit plain text, it inserts the wrong end of line format that will confuse *NIX systems and cause your scripts to error. Using VSCode or NotePad++ is better. On Linux systems, you can use any of your system's text editors. On Mac, Visual Studio Code is my recommended option as Mac can run shell scripts natively. 

At the start of your file, as in the first line, you need to put the following:

Code:
#!/bin/bash

This is commonly called the "shebang" and it tells what shell you're using. The most common is bash, but zsh can also be used if it's on your system. The vast majority of Linux and UNIX systems all have bash available.

Adding comments
Like coding in any other language, comments are essential. In shell scripting, you use a # at the beginning of the line. Shell does not have block comments so each comment line must start with #. For example:


Code:
# This is a comment
# And this is another
# And my final comment


Now you can add commands!

Doing stuff
Shell scripting is literally using the same commands you use while using the CLI of your Linux machine. Like for instance, this script will open the default Apache web directory and list the contents:

Code:
#!/bin/bash
# Move to the web root
cd /var/www/html/
# List it all out
ls -la

Pretty nifty, right?

Running your script
To run your script, save it as a .sh file - for example, myfirstscript.sh. Navigate to it via your CLI and run:

./myfirstscript.sh

and you should see it list out the contents of the web root (assuming you have files there).

That's it for now. Like I said, this is just a very basic introduction. I'll be back with more!  Smile
 Travis Newton
NodeSpace Owner
 Follow us on Twitter @NodeSpace
Client Area | Open Ticket | Knowledge Base
[Image: sudo-bare-metal-468x60.png]
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)