I haven’t been writing blogs since a long time now. But I’ve been learning a lot of good stuff working at Automattic (the company behind WP.com). So I plan to write and share stuff I learn here on this blog (at least one article on a daily or a weekly basis).
Today, I’ll be sharing something which I just learned from a YouTube video – Writing hello world using bash (shell scripting).
I’ll be writing this for Mac OS X but if you’re using Linux or Windows 10, you should be good. Now before you start, you can check the shells available to you by typing in the following command in the terminal –
[code] cat /etc/shells [/code]
Once you enter it, you should see all the shells available to you. I see this on my Mac operating system –
In this post, I’ll be specifically using bash. So it’s important to locate where bash is stored on your system. To do this, we will use the which command.
This will return the directory where bash is stored. For me this is –
[code] /bin/bash [/code]
Next just navigate to your desktop using the change directory (cd) command. And create a file called hello_world.sh using the touch command.
Now type the following to see a short list of files in your directory –
ls – al
I’m seeing this being returned in my terminal –
-rw-r–r– 1 omkarbhagat staff 0 Oct 23 03:01 hello_world.sh
This means, out of the three permissions (read r, write w, execute x) – the owner of the file has read, write; the group has read permission and others have read permission.
Just keep this information in mind and move to the next step. Go ahead and open your newly created file using textedit (or your preferred text editor). And then write the following code inside of it –
echo "Hello World"
In the above code, #! is something which is called shebang in Unix. We use that as first line to make use of bash and the 2nd line is self explanatory.
Save the file and run it in terminal using the following command –
[code] ./hello_world.sh [/code]
The moment you run it, you’ll see a permission denied error. If you remember, you still don’t have write permissions for this file. So you can now chmod it –
[code] chmod +x hello_world.sh [/code]
This will add an execute permission to all three types of user groups. And if you run ls -al again, you should be able to see the x permission there –
[code] -rwxr-xr-x@ 1 omkarbhagat staff 32 Oct 23 03:21 hello_world.sh [/code]
Now you can simply run or execute hello world again and the output will be Hello World on screen –