Shell Script
- A shell script is a file containing one or
more commands
- You could type those commands individually on the command line
- Here's the content of my first shell script:
- We have already encountered the [echo] command in
Command Types
- Now I have to give my file a name:
- do not choose a name that is another builtin or an external executable (e.g do not choose test)
- you can add .sh, so that it reminds you that this is a shell script. Note that the script does not need it, and it is not something many ppl do
Running the script using the source command
- You can run your script using the
source command:
1$ ls -l
2total 4
3-rw-rw-r-- 1 osboxes osboxes 18 Jan 17 09:02 hello
4$ cat hello
5echo Hello World!
6$ source hello
7Hello World!
8$
- source is a shell builtin, and it reads commands from the file you give it as a parameter, and executes them. The shell that is running those command is the current shell
- To make sure you understand the meaning of that, add the command
exit at the end of your script and run it
Running the script using the bash command
- You can run the script using the bash command:
1$ bash hello
2Hello World!
3$
- This is really running another shell process, so that the current shell waits until the new process end running. The new shell is running the commands in the script.
- As before, at the exit command and see what's happening
Running the script as a command
- The third option is to run the script as if it was a command.
- I should change the script to look like this:
1#!/bin/bash
2#
3
4echo Hello World!
5exit
- The first line starts with #! and is called a
shebang (the name is a mispronouncing of hash bang)
- It tells bash what kind of interpreter should be used to run this script (you can try a python script)
- Now, the file itself should behave like a program, since it is like you are running a binary file. So add execution permission for the user:
- Now you can run it (note that this directory is not part of the path):
1$ ./hello
2Hello World!
3$
- Note that this was running a new bash processes, so that the current bash process has not terminated.