Problem
Create a Hello World script in Bash.
tl;dr
nano helloworld.sh
Type in your script:
#!/bin/bash echo Hello World!
Hit Ctrl-O then Ctrl-X to save and exit the file. Then execute the script:
chmod +x helloworld.sh ./helloworld.sh
Solution
Simplest way of looking at a bash script is to consider it a macro. It's a simple list of commands that deploys command line arguments one by one. Any bash script begins with a hashbang and the path to bash:
#!/bin/bash
This tells the shell to execute any commands that follow the hashbang. You can run them on any flavour of UNIX, even OS X.
Creating a Bash scriptYou create a Bash script by making a new file with the extension .sh in a text editor of your choice:
nano helloworld.sh
Then add hashbang header and any code you want, such as:
#!/bin/bash echo Hello World!Running a Bash script
Navigate to the directory the script is located in, and run it with ./filename.sh command:
./helloworld.sh
Unfortunately, this will usually give you an error, or the bash script will just fail to execute:
# ./helloworld.sh -bash: ./helloworld.sh: Permission deniedPermission denied error
This happens because the file you created does not have "execute" permission (i.e. the system is not allowed to execute the file). To fix it, type in:
chmod +x helloworld.sh
You can now execute your script. Congratulations, you've written your first Bash script!