Skip to Content

A Home For Your Bash Scripts

Posted on 2 mins read

Bash scripting has always been on my to-do list. It’s a great way to alleviate repetitive command line tasks. Plus, can help optimize your workflow. The first step in this process is being able to call scripts from anywhere. This post will cover just that.

Hello World

Before we can call a script we need to write one. Head to your editor of choice and create a script titled helloworld.sh with the following code.

#!/bin/bash
echo "hello, $USER. I wish to list some files of yours"
echo "listing files in current directory, $PWD"
ls

The only line worth mentioning is the first - #!/bin/bash/. This lets the shell know which interpreter to run. For a more detailed breakdown check out this Stack Overflow post.

Get Permission

Now that we have a script we need to be able to run it. In essence, we need to make the script executable. To do this we will use chmod. In order to do this next step you’ll need to head to your terminal.

chmod u+x helloworld.sh

What this command does is allow the current user, and only the current user, executable permission. To allow anyone to use this script, you would use chmod a+x filename.

Running A Script

Now that we have an awesome script and the correct permission we are good to go! In the same folder as your script run the following command.

./helloworld.sh

output

Congrats! You are almost a bash scripting pro. However, if you try to go and navigate somewhere else and call this script…well, whomp whomp. So how do we fix this?

Anywhere & Everywhere

The first thing to do is create a /scripts directory.

cd
mkdir scripts

Now, you’ll need to specify this path in your .bashrc or .zshrc depending on what you use.

export PATH=$PATH:~/scripts

After this you are set! You should be able to head anywhere and call your script. In order to do so, you’ll just need to type scriptname.sh.

helloworld.sh

Bonus

Now that you’ve got the structure down it’s time to learn some bash. Here’s a few resources to tackle just that!