Writing your first Linux shell script enables you to automate tasks and streamline your workflow. This tutorial guides you through creating a simple bash script, from choosing an editor to adding logic and control structures. By the end, you'll have written and executed your first working shell script.
How to Write Your First Shell Script
-
Step 1: Choose a Text Editor
Select a text editor to write your script. Popular options include Vim, Emacs, Nano, or graphical editors like Sublime Text or VSCode.
-
Step 2: Start with a Shebang
At the beginning of your script, include a shebang line to specify the interpreter. For bash scripts, use:
#!/bin/bashThis tells the system to interpret the script using the bash shell.
-
Step 3: Write Your Script
Add commands and logic to achieve your desired functionality. Here's a simple example that prints "Hello, World!" to the terminal:
#!/bin/bash echo "Hello, World!" -
Step 4: Save Your Script
Save your script with a
.shextension to indicate that it is a shell script. For example, name ithello_world.sh. -
Step 5: Make Your Script Executable
Before you can run your script, make it executable using the
chmodcommand:chmod +x hello_world.sh -
Step 6: Run Your Script
Execute your script from the command line:
./hello_world.shIf everything is set up correctly, you should see "Hello, World!" printed to the terminal.
-
Step 7: Add Comments
Comments are essential for documenting your code and making it more understandable. Add comments to your script using the
#symbol:#!/bin/bash # This is a simple script that prints "Hello, World!" echo "Hello, World!" -
Step 8: Use Variables and Arguments
You can use variables to store data and arguments passed to your script. Here's an example that takes a name as an argument and prints a personalized greeting:
#!/bin/bash # This script takes a name as an argument and prints a greeting NAME=$1 echo "Hello, $NAME!"Run the script with a name argument:
./hello.sh JohnThis would print "Hello, John!".
-
Step 9: Add Control Structures
Use control structures like
if,else,elif,for, andwhileto add conditional logic and looping to your scripts. Here's a simple example using anifstatement to check if a file exists:#!/bin/bash # Check if a file exists FILE="example.txt" if [ -f "$FILE" ]; then echo "$FILE exists." else echo "$FILE does not exist." fiThis script checks if a file named
example.txtexists in the current directory and prints a corresponding message. -
Step 10: Learn and Experiment
Shell scripting is a vast topic, and there's always more to learn. Experiment with different commands, techniques, and scripts to improve your skills and understanding.