Join Scott Simpson for an in-depth discussion in this video Creating a basic Bash script, part of Learning Bash Scripting.
Frequently, if you're creating or editing a Bash script, you'll be doing so in a terminal window. I'm using the nano editor here on my system, and I'll create a file by typing nano my.sh. The .sh on the end, signifies that it's a shell script. And of course, we'll want to put the shebang line in first. Next, I'll add a comment to describe what the script does. It's a good practice to document things as you write them, so you're not faced with coming back months or years later and trying to figure out what a script is for. At this point, we're ready to write something that does something.
And as it turns out, we already know a whole bunch of Bash commands. Let's just use a basic one for now. That's just the command to list the current directory, so we know what to expect out of the script. I'll save the file with Ctrl+O, and then exit, which is Ctrl+X. Back at the command line, if I type ls, I can see that I've got the script here. But I can't just type the name of the script to run it. I have to use an interpreter for that. So I can type bash my.sh. And we see the contents of this folder, just like we'd expect. But most of the time, you won't want to type out bash in front of your script.
So let's take advantage of that shebang line, which tells the system where the bash interpreter is. I'll type chmod +x my.sh to make the script executable. And now I can just run it by typing ./my.sh. We need the ./ since the current working directory isn't part of the path environment variable. If we put the script somewhere that is, like usr/bin, then I can run it just by typing the name. But we wouldn't really want to do that in practice, and that's getting a little ahead of ourselves. Of course, now I can do nano my.sh and jump back into the script and make changes if I need to, but for now, let's leave it as is.
- What is Bash?
- Managing output with grep, awk, and cut
- Understanding Bash script syntax
- Creating a basic Bash script
- Displaying text with "echo"
- Working with numbers, strings, and arrays
- Reading and writing text files
- Working with loops
- Using functions
- Getting user input during execution
- Ensuring a response