Create, configure and run a bash script

Scripting


NOTE: The commands given in the scripting section are to be put into the text editor and not in the terminal unless instructed otherwise.
Bash is primarily a scripting language, so it would be a crime not to talk about scripting. Let's dive straight in with a bash script. More precisely the infamous "Hello World" script. You can create a bash script by opening your favorite text editor to edit your script and then saving it (typically the .sh file extension is used for your reference, but is not necessary. In our examples, we will be using the .sh extension).
 #!/bin/bash         

echo "Hello, World"

The first line of the script just defines which interpreter to use. NOTE: There is no leading whitespace before #!/bin/bash. That's it, simple as that. To run a bash script you first have to have the correct file permissions. We do this with chmod command in terminal (change mode) as follows:
chmod a+x /where/i/saved/it/hello_world.sh   #Gives everyone execute permissions
# OR
chmod 700 /where/i/saved/it/hello_world.sh #Gives read,write,execute permissions to the Owner

This will give the file the appropriate permissions so that it can be executed. Now open a terminal and run the script like this:
/where/i/saved/it/hello_world.sh

Hopefully you should have seen it print Hello, World onto your screen. If so well done! That is your first Bash script.
TIP If you type:
pwd

You will see the directory that you are currently working in (pwd stands for 'print working directory'). If your current working directory is /where/i/saved/it/, then you can shorten the above command to:
prompt$ pwd
/where/i/saved/it
prompt$ ./hello_world.sh

So, all you need is add "#!/bin/bash" in the top, write down some commands, add execute privilege to the file and run it as ./filenname.sh.

Σχόλια

Δημοφιλείς αναρτήσεις από αυτό το ιστολόγιο

Δεν δουλεύει το Internet σωστά? Δείτε τι σημαίνουν τα LED λαμπάκια στο router σας

Κόπηκε το Internet? Τα 5 πιο πιθανά αίτια για να το επαναφέρεις άμεσα

Vodafone H300S router: Πλήρης οδηγός χρήσης του εξοπλισμού