In this section will look at how to create shell scripts, in order to run them we will make them executable - just like commands.
Shell scripts are files created using a text editor such as Nano, the files are saved with a .sh extension to indicate that they are shell scripts.
The steps below step through how to create a simple shell script.
Open a new file in Nano, enter the commands below and save as hello_world.sh
#!/bin/bash
# This is a very simple hello world script.
echo "Hello, world!"
We can use chmod
to change permissions on the script and make it executable:
[user@host ~]$ chmod u+x hello_world.sh
[user@host ~]$ ls -l hello-world.sh
-rwxr--r-- 1 user ccaas0 30 Mar 31 17:10 hello_world.sh
To run the script:
[user@host ~]$ ./hello_world.sh
hello world!
What’s with the “./” ?
Remember the PATH! - we are instructing bash to run the script in the current location.
If you want to be able to make your script work like a command, you need the directory it is in to be in your PATH
[user@host ~]$ mkdir ~/scripts
[user@host ~]$ PATH=$PATH:$HOME/scripts
[user@host ~]$ export PATH
You can control your script’s behaviour with arguments you pass to it when you run it.
An example might be:
[user@host ~]$ ./script.sh var1 var2
Within the script: $1 contains “var1” $2 contains “var2”
The script looks like this:
#!/bin/bash
echo The first argument is $1
echo The second argument is $2
echo And together they make ${1}${2}
And here it is in use:
[user@host ~]$ ./var-script green house
The first argument is green
The second argument is house
And together they make greenhouse
Next activity: Exercises - File permissions.