Chapter 6: Shell Scripting 101
Up until now, you have been typing commands one by one. But what if you need to run a sequence of 50 commands every single morning to back up your server, clear the logs, and update your software? Typing them manually is a waste of time.
Welcome to Shell Scripting. A shell script is simply a standard text file containing a list of terminal commands. When you run the file, the Linux kernel reads it from top to bottom and executes every command automatically at lightning speed.
1. The Anatomy of a Script
Every bash script must start with a very specific line of code at the absolute top of the file, known as the Shebang. It looks like this:
The #! tells the Linux operating system, "Hey, do not read this like a normal text file. Send this code to the Bash interpreter located at /bin/bash to be executed."
2. Writing the Logic
Once you have your shebang, you can write any command you would normally type into the terminal. You can also create Variables to store data, just like in Python or JavaScript.
3. The Execution Problem
If you save that code into a file called matrix.sh and try to run it, it will fail. Why? Because of the security permissions we learned about in Chapter 4! By default, Linux creates text files without "Execute" privileges to stop malicious code from running automatically.
Before you can run a script, you must grant it execution rights using the chmod command:
4. Pulling the Trigger
Once the file has execute permissions (which you can verify by seeing the x in ls -l), you run it by typing a dot and a forward slash, followed by the file name.
Why the dot-slash? The dot represents your current directory. You are explicitly telling the terminal, "Execute the file named matrix.sh that is sitting exactly right here."
🔥 Try It Yourself
We have planted a pre-written script inside your projects directory. Your final test is to read it, check its permissions, and execute it.
- Type
cd projectsto enter the directory. - Type
cat script.shto look at the source code inside the file. - Type
ls -lto verify that the file hasx(execute) permissions. - Type
./script.shto execute the script and complete your training!