Let's dive right in and create your very first shell script. Follow these steps:
nano myfirstscript.sh
#!/bin/bash
echo "Hello, World!"
Congratulations! You've just written your first shell script.
The first line of our script, #!/bin/bash
, is called the "shebang" or "hashbang". It tells the system which interpreter to use to run the script. In this case, we're specifying the Bash shell.
Before we can run our script, we need to make it executable. Use the following command:
chmod +x myfirstscript.sh
This command gives the file execute permissions.
To run your script, use one of these methods:
The first method uses the shebang to determine the interpreter, while the second explicitly uses Bash.
Comments in shell scripts start with a #. They're ignored by the shell and are used to explain your code. For example:
# This is a comment
echo "This will be printed" # This is an inline comment
Basic syntax rules:
Let's create a slightly more advanced script:
#!/bin/bash
# This script greets the user and tells them the current date
# Get the current user's name
username=$(whoami)
# Get the current date
current_date=$(date +"%Y-%m-%d")
# Print greeting and date
echo "Hello, $username!"
echo "Today's date is: $current_date"
This script introduces variables and command substitution, which we'll explore more in future articles.
You've now taken your first steps into the world of shell scripting! You've learned how to create, make executable, and run a script. You've also been introduced to comments, basic syntax, and a glimpse of more advanced concepts.
In our next article, we'll dive deeper into working with variables and user input. Keep practicing with simple scripts, and soon you'll be automating tasks like a pro!