0
0
Bash Scriptingscripting~15 mins

First Bash script in Bash Scripting - Deep Dive

Choose your learning style9 modes available
Overview - First Bash script
What is it?
A Bash script is a simple text file containing a series of commands that the computer can run one after another. It helps automate tasks by running these commands automatically instead of typing them manually. Writing your first Bash script means creating this file and making it ready to run on your computer. This is the starting point for automating repetitive tasks on systems that use the Bash shell.
Why it matters
Without Bash scripts, you would have to type every command manually each time you want to do a task, which is slow and error-prone. Bash scripts save time, reduce mistakes, and make complex tasks easy to repeat. They are especially useful for system maintenance, backups, and setting up environments. Learning to write your first Bash script opens the door to powerful automation that can make your computer work smarter for you.
Where it fits
Before learning Bash scripting, you should know basic command-line usage and simple commands in a terminal. After mastering your first Bash script, you can learn about variables, loops, conditionals, and functions in Bash to create more complex scripts. Eventually, you can explore advanced scripting techniques and automation tools that build on these basics.
Mental Model
Core Idea
A Bash script is like a recipe that tells your computer exactly what steps to follow, one by one, to complete a task automatically.
Think of it like...
Imagine you want to bake a cake. Instead of remembering each step every time, you write down the recipe. The recipe guides you through mixing, baking, and decorating without forgetting anything. A Bash script is that recipe for your computer.
┌───────────────┐
│  Bash Script  │
├───────────────┤
│ 1. Command A  │
│ 2. Command B  │
│ 3. Command C  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  Computer runs│
│ commands in   │
│ order         │
└───────────────┘
Build-Up - 7 Steps
1
FoundationCreating a simple script file
🤔
Concept: Learn how to create a text file that will hold your Bash commands.
Open a terminal and use a text editor like nano or vim to create a new file named 'first_script.sh'. For example, run: nano first_script.sh. This file will contain the commands you want to automate.
Result
A new empty file named 'first_script.sh' is created and ready for editing.
Knowing how to create the script file is the first step to automation; without the file, you cannot save or run commands automatically.
2
FoundationAdding commands to the script
🤔
Concept: Write simple commands inside the script file to perform tasks.
Inside 'first_script.sh', type the following lines: #!/bin/bash echo "Hello, world!" This script tells the computer to print 'Hello, world!' when run. The first line '#!/bin/bash' tells the system to use Bash to run the script.
Result
The script file now contains a command to print a message and a line specifying the interpreter.
Including the interpreter line ensures the script runs with the correct program, and adding commands is how you tell the computer what to do.
3
IntermediateMaking the script executable
🤔
Concept: Change the script file permissions so the system can run it as a program.
In the terminal, run: chmod +x first_script.sh. This command gives the script permission to be executed. Without this, the system will not allow you to run the script directly.
Result
The script file becomes executable, allowing you to run it as a program.
Understanding file permissions is key to running scripts; execution permission is a security feature that prevents accidental or unauthorized runs.
4
IntermediateRunning the Bash script
🤔
Concept: Learn how to execute the script and see its output.
Run the script by typing: ./first_script.sh in the terminal. The './' means 'run the script in the current folder'. You should see the message 'Hello, world!' printed on the screen.
Result
The terminal displays: Hello, world!
Running the script confirms your commands work as expected and shows how scripts automate tasks by executing multiple commands.
5
IntermediateUsing comments to explain code
🤔
Concept: Add comments to your script to explain what each part does.
In your script, add lines starting with '#' to write notes. For example: #!/bin/bash # This prints a greeting message echo "Hello, world!" Comments are ignored when running the script but help you and others understand the code.
Result
The script now contains comments that explain its purpose.
Comments improve script readability and maintainability, which is important as scripts grow more complex.
6
AdvancedUnderstanding the shebang line
🤔Before reading on: do you think the '#!/bin/bash' line is required for the script to run? Commit to yes or no.
Concept: Learn why the first line '#!/bin/bash' is important and what happens if it is missing.
The line '#!/bin/bash' is called the shebang. It tells the system which program to use to run the script. Without it, the system might use a different shell or fail to run the script properly. This line ensures your script runs consistently on systems with Bash installed.
Result
Scripts with the shebang run reliably with Bash; without it, behavior may vary or cause errors.
Knowing the shebang's role prevents confusing bugs caused by running scripts with the wrong shell or interpreter.
7
ExpertRunning scripts without execution permission
🤔Before reading on: can you run a Bash script without making it executable? Commit to yes or no.
Concept: Discover alternative ways to run scripts without changing file permissions.
You can run a script by explicitly calling Bash and passing the script as an argument: bash first_script.sh. This runs the script without needing execution permission on the file itself. This method is useful when you cannot change permissions or want to test scripts quickly.
Result
The script runs and prints 'Hello, world!' even if it is not executable.
Understanding this method helps in environments with strict permissions and clarifies how the shell executes scripts.
Under the Hood
When you run a Bash script, the system reads the first line to find the interpreter (like /bin/bash). Then it opens the script file and reads commands line by line, executing each in order. The shell manages variables, input/output, and command execution. Execution permission is checked by the operating system before running the script to ensure security.
Why designed this way?
The shebang mechanism was designed to allow scripts to specify their interpreter explicitly, enabling multiple scripting languages to coexist. Execution permissions protect users from accidentally running harmful scripts. This design balances flexibility, security, and clarity in script execution.
┌───────────────┐
│ User runs    │
│ ./script.sh  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ OS checks    │
│ execution    │
│ permission   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Reads shebang │
│ (e.g., /bin/bash)│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Bash reads   │
│ script lines │
│ executes     │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Is the shebang line optional for all Bash scripts? Commit to yes or no.
Common Belief:Many think the shebang line is optional and scripts will always run fine without it.
Tap to reveal reality
Reality:Without the shebang, the system may use a different shell or fail to run the script properly, causing unexpected behavior.
Why it matters:Skipping the shebang can lead to bugs that are hard to diagnose, especially when scripts run differently on various systems.
Quick: Can you run a script by just typing its name without './' if it's in the current directory? Commit to yes or no.
Common Belief:Some believe you can run a script by typing its name alone if it's in the current folder.
Tap to reveal reality
Reality:By default, the current directory is not in the system's PATH, so you must use './' to run scripts in the current folder.
Why it matters:Not using './' leads to 'command not found' errors, confusing beginners about script execution.
Quick: Does making a script executable mean it can run anywhere without specifying the path? Commit to yes or no.
Common Belief:People often think making a script executable allows running it from any location by just its name.
Tap to reveal reality
Reality:Execution permission alone is not enough; the script must be in a directory listed in the PATH environment variable to run by name alone.
Why it matters:Misunderstanding this causes frustration when scripts don't run as expected from different folders.
Quick: Can you run a script without execution permission by calling the interpreter explicitly? Commit to yes or no.
Common Belief:Many believe execution permission is always required to run a script.
Tap to reveal reality
Reality:You can run a script without execution permission by running 'bash script.sh', which calls the interpreter directly.
Why it matters:Knowing this helps in restricted environments and clarifies how scripts are executed.
Expert Zone
1
Scripts with the shebang line run with the specified interpreter even if your default shell is different, preventing subtle bugs.
2
Execution permission is a file system attribute, separate from ownership or read/write permissions, and affects security and usability.
3
Running scripts via 'bash script.sh' bypasses execution permission but may behave differently if the script relies on environment variables or shell options.
When NOT to use
For very complex automation or cross-platform tasks, Bash scripts may become hard to maintain. In such cases, using higher-level languages like Python or automation tools like Ansible is better. Also, avoid Bash scripts on systems without Bash installed or where performance is critical.
Production Patterns
In production, first Bash scripts evolve into modular scripts with functions, error handling, and logging. They are often combined with cron jobs for scheduled tasks or integrated into CI/CD pipelines for automation. Scripts are stored in version control and tested to ensure reliability.
Connections
Makefiles
Builds-on
Understanding Bash scripts helps grasp Makefiles, which use shell commands to automate building software projects.
Python scripting
Alternative approach
Knowing Bash scripting clarifies when to switch to Python for more complex automation requiring better readability and libraries.
Cooking recipes
Conceptual analogy
Recognizing that scripts are like recipes helps understand the importance of order, clarity, and repeatability in automation.
Common Pitfalls
#1Trying to run the script without making it executable.
Wrong approach:./first_script.sh # Output: bash: ./first_script.sh: Permission denied
Correct approach:chmod +x first_script.sh ./first_script.sh # Output: Hello, world!
Root cause:Not understanding that execution permission is required for scripts to run directly.
#2Forgetting the shebang line and running the script expecting Bash behavior.
Wrong approach:first_script.sh without '#!/bin/bash' # Output: Errors or unexpected behavior if default shell differs
Correct approach:#!/bin/bash first_script.sh # Output: Hello, world!
Root cause:Not realizing the system needs to know which interpreter to use.
#3Running the script by typing its name without './' in the current directory.
Wrong approach:first_script.sh # Output: bash: first_script.sh: command not found
Correct approach:./first_script.sh # Output: Hello, world!
Root cause:Misunderstanding how the shell searches for commands using the PATH variable.
Key Takeaways
A Bash script is a text file with commands that automate tasks by running them in order.
The shebang line '#!/bin/bash' tells the system to use Bash to run the script, ensuring consistent behavior.
Scripts must have execution permission to run directly, but you can also run them by calling Bash explicitly.
Using './' before the script name runs it from the current directory because the shell does not search there by default.
Comments in scripts improve clarity and help maintain and share your automation with others.