Layla

How to Make a Bash Script Executable in Linux

Cover Image for How to Make a Bash Script Executable in Linux

Hey coders! 🧡

I completed my Linux Operating System course this semester (with an A!!!!) 🥳, and wanted to blog about a few fun things I've learned in the class!

Let's talk about how you can make a Bash script executable 🤠


Step 1: Create a new text file

First, we have to create a file to write our script in. I use the Vim editor mainly, so I'll be demonstrating the example within Vim!

To create a new file in Vim, type: vi MyNewScript.sh in the command line, like below

Screen Shot 2021-12-05 at 2.03.56 PM.png


Step 2: Add #!/bin/bash

Don't forget to add your sha-bang to the top of your Vim (or Nano) file! This is key for 'making it executable'.

Screen Shot 2021-12-05 at 2.10.53 PM.png


Step 3: Add your script!

This is where the fun begins 🤠 you can easily automate simple processes in a function within your Bash script! Here's an example ⤵️

Screen Shot 2021-12-05 at 2.45.26 PM.png

In the above script example, I created a function, CreateDir(). When called, CreateDir should accept a new directory name as a command-line argument and then create a new directory (if you don't already have a directory created with the same name!)


Step 4: At the command line, run chmod u+x

Screen Shot 2021-12-05 at 2.27.36 PM.png

Wondering what chmod u+x does? It grants only the owner of that file execution permissions. (Basically making it only executable for the owner of the file.)


Step 5: Run your script!

To run your new script, simply type ./YourScriptFileName.sh! (The key is using ./ in front of your script file.)

Screen Shot 2021-12-05 at 2.41.36 PM.png

As you can see above, the script successfully catches a duplicate directory name, and won't allow it to be created. 🤠 yeehaw!


and voila!! That is the simple process of making a script executable in Linux 🥰

Stay tuned for more articles on Vim in Linux, cronjobs, etc.! I have some fun Linux content planned 🧡

If this helped you, give me follow on Twitter here! I hope you have an amazing rest of your day!!