Shell scripting. It is the single most powerful productivity tool for any Linux administrator, and it is a core part of LPIC-1 because it turns a slow, error-prone manual process into a fast, repeatable automaton. Without shell scripts, you would type every command by hand, every time, for every file — a nightmare that the exam wants to make sure you never have to endure.
Jump to a section
A simple way to picture Shell Scripting Basics
Have you ever stood in front of an open fridge on a Tuesday night, staring at a bag of spinach and some leftover rice, wondering what on earth you could make for dinner? You know you have the ingredients, but the thought of chopping, stirring, and cleaning up after a long day is exhausting. What if you had spent just one hour on Sunday prepping everything? You would have a container of chopped veggies, a jar of sauce, and cooked quinoa ready to go. Tuesday's dinner then becomes a simple job of grabbing, combining, and heating. That is exactly what a shell script does for your computer's operating system. The shell is your kitchen counter, and each command you type — like 'ls' to list files or 'cd' to change directories — is one ingredient or one step in a recipe. Instead of typing those commands one by one every time you need to do a repetitive task, like backing up a folder or renaming a hundred photos, you write a script. The script is your meal prep. It stores the sequence of commands, loops over the same action for each file, checks if a condition is met (like 'if the folder exists'), and wraps it all neatly into a reusable function. One Sunday session of scripting saves you from typing the same thing over and over every week. Your computer does the boring, repetitive chopping so you have time to think about the bigger picture.
A shell script is nothing more than a plain text file that contains a sequence of Linux commands. When you run that file, the shell (the program that reads and executes your commands, like Bash) reads each line and does what it says, one after the other. Think of it as a to-do list for your computer. Instead of you typing 'mkdir new_folder' and then 'cd new_folder' and then 'nano report.txt' one by one, you put all three commands in a file called 'setup.sh', make it executable, and run it. The computer does the rest.
To create a shell script, you need three things: a text editor (like nano or vim), the 'shebang' line at the top of the file, and the correct file permissions. The shebang line looks like '#!/bin/bash'. It tells the system which shell interpreter to use. Without it, the system might guess wrong and your script could fail with confusing errors. After you write your commands, you must make the script executable with the command 'chmod +x scriptname.sh'. This tells Linux 'yes, this file is allowed to be run as a program'.
Variables are a fundamental building block. A variable is a named container that holds data. You assign data to it with an equals sign, like 'name="Alice"'. Notice there are no spaces around the equals sign. To use that value later, you put a dollar sign in front of the variable name, like 'echo $name'. This will print 'Alice' on the screen. Variables let you write scripts that work with different data without changing the script itself. Instead of hard-coding a file path, you use a variable and set it once at the top of the script.
Loops let you repeat a set of commands multiple times. The most common loop is the 'for' loop. It looks like this:
for file in *.txt do echo "Processing $file" done
This loops over every file that ends with '.txt' in the current directory, runs the 'echo' command for each one, and substitutes the current file's name into the '$file' variable. There is also the 'while' loop, which runs as long as a condition is true, like 'while [ $count -lt 10 ]'. You almost always need a counter variable and a way to change that condition inside the loop, or it will run forever (an 'infinite loop') and you will have to press Ctrl+C to stop it.
Conditionals let your script make decisions. The basic structure is 'if', 'then', 'else', and 'fi' (which is 'if' backwards). For example:
if [ -f /etc/passwd ] then echo "The file exists" else echo "File not found" done
This checks if the file /etc/passwd exists ('-f' means 'is a file'). If it does, the script prints one message; otherwise, it prints another. The square brackets are actually a command called 'test'. You must have spaces inside them, or the test will fail. Conditionals let your script react to different situations.
Functions are mini-scripts inside your script. You define one with 'myfunction() { commands; }'. Then you 'call' it by typing its name. Functions are brilliant for avoiding repetition. If you need to print a timestamped log message ten times, write one function for that task and call it whenever needed. If you later want to change the format of the timestamp, you change it in one place instead of ten.
Shell scripting replaces the tedious, error-prone work of typing dozens or hundreds of commands manually. It is how system administrators automate backups, monitor server health, process log files, and deploy software. It makes the computer do the boring work while the human does the thinking.
Plan the Script
Before typing a single line, decide what the script must accomplish. Write down the steps you would take manually. This planning prevents logic errors and helps you identify which commands, variables, and loops you will need.
Create the Script File
Use a text editor like 'nano' or 'vim' to create a new file, for example 'nano myscript.sh'. The file name is arbitrary but should be descriptive. Do not forget the shebang line as the very first line.
Write the Commands and Logic
Add your commands in the order they should run. Use variables for any value that might change. Add loops to repeat actions and conditionals to handle different situations. Use functions to organise reusable chunks.
Make the Script Executable
Run 'chmod +x myscript.sh' in the terminal. This sets the executable permission bit, allowing you to run the script with './myscript.sh'. Without this step, you will get a 'Permission denied' error.
Test the Script
Run the script in a safe environment (like a test directory, not your home folder). Check that the output matches your expectations. If something goes wrong, add 'echo' statements to print intermediate variable values so you can see where the logic breaks.
Debug and Iterate
If the script does not work correctly, use 'bash -x myscript.sh' to run it in debug mode. This prints each command before it executes, showing you exactly where the script diverges from your plan. Fix errors, then test again.
Imagine you work for a small company that runs its website on a Linux server. Every night, the server needs to be backed up. The manual way would be to SSH into the server, type 'tar -czf backup_$(date +%Y%m%d).tar.gz /var/www', then copy that file to a backup drive. If you do it once, fine. If you do it every single night for a year, you will eventually forget, typo a path, or fall asleep. A shell script handles this perfectly.
Here is what a real IT professional does. First, she writes a script called 'nightly_backup.sh' in her home directory. The script starts with '#!/bin/bash'. Then she sets a variable for the source directory: 'SOURCE_DIR="/var/www"'. And one for the backup destination: 'BACKUP_DIR="/mnt/backups"'.
Then she uses a conditional to check if the backup drive is mounted. If the drive is not mounted, the script should not run. The command looks like 'if mount | grep -q /mnt/backups'. If it fails, the script prints a warning and exits with a non-zero exit code (like 'exit 1'), which would trigger an alert to her team.
Next, she uses a 'for' loop to check which old backups exist. She might decide to keep only the last 30 backups. The loop iterates over backup files, counts them, and if there are more than 30, deletes the oldest ones using 'rm'. This prevents the backup drive from filling up.
Then comes the actual backup command: she runs 'tar -czf ${BACKUP_DIR}/backup_$(date +%Y%m%d_%H%M%S).tar.gz $SOURCE_DIR'. She wraps the backup action inside a function called 'create_backup' so that if she ever needs to change how the backup is compressed, she edits one function instead of the whole script.
Finally, she schedules the script using 'cron'. She runs 'crontab -e' and adds a line: '0 2 * * * /home/admin/nightly_backup.sh'. This tells Linux to run that script every day at 2:00 AM. From that point on, she never thinks about backups unless the script fails. That is the real power of shell scripting: it turns human vigilance into machine reliability.
The LPIC-1 exam objective 103.4 specifically tests your ability to write simple shell scripts using variables, loops, conditionals, and functions. The exam does not ask you to write a massive 200-line program. Instead, it gives you short scenarios and asks you to identify the correct syntax, or to spot the error in a given script. You will see a lot of multiple-choice questions that show a small script snippet and ask 'What is the output?' or 'Why does this script fail?'.
Here are the exact concepts they love to test:
The shebang line: they will show a script missing '#!/bin/bash' and ask why it runs incorrectly. The correct answer is almost always 'the shell interpreter was not specified'.
Variable assignment: they love to trap you with spaces. 'name = "Alice"' is wrong because of the spaces around the equals sign. The correct form is 'name="Alice"'. They will also test that you must use '$' to reference a variable but not when assigning it.
The 'test' command inside square brackets: they will show '[ $count -lt 10 ]' without spaces and ask what the error is. The answer: you need spaces after '[' and before ']', like '[ $count -lt 10 ]'.
The syntax of 'for', 'if', and 'while' loops: they will give you a loop that is missing the 'do' keyword or the 'done' keyword. The correct answer will point out that missing 'do' causes a syntax error.
Functions: they test that a function is defined with 'name()' and that you call it by just typing the name (no parentheses around the call, unlike some other languages).
Exit codes: they may ask what happens if a script ends without an explicit 'exit' statement. The return value is the exit status of the last command that was executed.
Common traps include: using 'echo $1' when the script expects a command-line argument but the argument might be missing (they will test your awareness of checking argument count with '$#'). Another trap is infinite loops: they might show a 'while' loop with a condition that never changes. The correct action is to recognise that the loop will never stop.
Memorise these patterns absolutely: 'if [ condition ]; then', 'for var in list; do', 'while [ condition ]; do', 'function_name() { command; }', and the shebang '#!/bin/bash' (including the exclamation mark and the leading slash).
A shell script is a plain text file containing commands that the shell reads and executes sequentially, like a to-do list for your Linux system.
The first line of every Bash script should be '#!/bin/bash' to tell the system which interpreter to use, and you must set the executable permission with 'chmod +x'.
Variables are assigned without a dollar sign ('name=value') and referenced with a dollar sign ('$name'), and you must always quote variable expansions to prevent word splitting.
A 'for' loop iterates over a list of items and runs a block of commands for each item, while a 'while' loop repeats as long as a condition remains true.
Conditionals using 'if', 'then', 'else', and 'fi' let your script make decisions based on the success or failure of commands or file tests like '-f' to check if a file exists.
Functions group related commands under a single name, allowing you to reuse code without repeating yourself, which makes scripts shorter and easier to maintain.
These come up on the exam all the time. Here's how to tell them apart.
Variable Assignment
Uses '=' with no spaces, e.g., 'name="Alice"'
Reads as 'name gets the value Alice'
Produces no output by itself
Variable Reference
Uses '$' before the name, e.g., 'echo $name'
Reads as 'substitute the value of name here'
Outputs the value, like 'Alice'
Single Quotes
Preserves all characters literally
$variable does not expand inside single quotes
Use for strings that must be exact
Double Quotes
Allows variable expansion and command substitution
$variable becomes its value inside double quotes
Use when you need the value of a variable
Running with bash
Explicitly uses the Bash interpreter
Ignores the shebang line
Works even if the file is not executable
Running with ./
Uses the shebang line to determine interpreter
Requires the file to be executable
More portable and standard for scripts
Mistake
I must use the '.sh' file extension for a shell script to work.
Correct
The file extension is irrelevant to Linux. The system determines how to run the file by reading the shebang line ('#!/bin/bash') and the executable permission bit. A script named 'backup' works identically to 'backup.sh'.
Windows uses file extensions to determine file type, so beginners naturally assume Linux does the same. They also see tutorials using '.sh' everywhere and think it is mandatory.
Mistake
Variables in a shell script are permanent and will stay set after the script finishes.
Correct
Variables defined in a shell script are local to the shell session that runs the script. When the script ends, those variables disappear. To make a variable available to other scripts or the parent shell, you must use 'export' to turn it into an environment variable.
Beginners are used to global variables from some other programming languages, and they do not understand that each shell script runs in its own child process (a subshell).
Mistake
A script that has no syntax errors will always run correctly and produce the intended result.
Correct
A script can have perfect syntax but still fail due to logic errors, missing dependencies, incorrect file paths, or insufficient permissions. For example, using 'rm -rf $DIR/*' when $DIR is empty will delete everything in the current directory.
New learners equate 'no error message' with 'no problem'. They do not yet grasp the difference between syntax (grammar) and semantics (meaning).
Mistake
The 'bash' command and './script.sh' are identical ways to run a script.
Correct
'bash script.sh' runs the script with the Bash interpreter regardless of the shebang line. './script.sh' uses the shebang line to decide which interpreter to run. If the shebang is missing or wrong, './script.sh' might fail, but 'bash script.sh' will still work.
Beginners do not understand the role of the shebang line. They see both methods work in simple cases and assume they are interchangeable.
Mistake
Quoting variables is only needed if the variable contains spaces.
Correct
Always quote variable expansions like "$VAR" to prevent word splitting and glob expansion. Even if the variable contains a single word right now, it might contain a special character later (like a wildcard '*'), and the unquoted expansion could cause unexpected behaviour or accidental file deletion.
This is subtle. Beginners test with simple strings like 'hello', and unquoted use works fine, so they think quoting is optional. They only discover the problem when they encounter a filename with spaces or a wildcard.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
The shebang line is the very first line of a script, starting with '#!' followed by the path to the interpreter, like '#!/bin/bash'. It tells the operating system which program should run the file. Without it, the system may use the wrong interpreter or refuse to run the script.
You probably forgot the dollar sign when referencing the variable. Variables are assigned as 'var=value' but must be referenced as '$var'. Also check that there are no spaces around the equals sign in the assignment.
Inside the script, use '$1' for the first argument, '$2' for the second, and so on. '$0' is the script name. '$#' gives the number of arguments. Always check '$#' at the start to ensure the user provided the required arguments.
Single quotes preserve every character literally inside them, so '$name' inside single quotes is the literal string '$name'. Double quotes allow variable expansion and command substitution, so "$name" becomes the value of the variable.
Run the script with 'bash -x scriptname.sh'. This prints every command as it executes, with a '+' prefix. You can also add 'set -x' at the top of your script to enable debug mode from inside the script, and 'set +x' to turn it off.
Yes, a shell script can run any command you can type in the terminal, including other scripts, compiled programs like 'gcc', or system utilities like 'tar' and 'grep'. That is the whole point: it is a way to orchestrate other tools.
You've finished Shell Scripting Basics. Continue through the LPIC-1 study guide to build a complete picture of the exam.
Done with this chapter?