# A Home For Your Bash Scripts

Kade Killary · 2017.12.27 · 2 minutes until it's over

Improving at Bash scripting is always on my to-do list. It’s a great way to alleviate repetitive command line tasks, while optimizing common workflows. 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.

#!/usr/bin/env 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 - #!/usr/bin/env 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

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 /bin directory.

cd
mkdir bin

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

export PATH="$PATH:$HOME/bin"

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 <your_script_name>.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!