...
Exercise 1 - Hello world
Below is the easiest a simple shell script in the world. Create and run this script.
...
that takes one argument (the text to print after "Hello") and echos it.
- The first line tells the shell which program to use to execute this file (here, the bash program).
- The 2nd line sets the shell variable TEXT to the first command line argument.
- The 3rd line defaults the value of TEXT to the string "Shell World" if no command line argument is provided.
- Remaining lines echo some text, substituting the value passed in on the command line.
| Code Block |
|---|
#!/bin/bash
TEXT=$1
: ${TEXT:="Shell World"}
echo "-------------------"
echo "Hello, $TEXT!"
echo "-------------------"
|
Open your favorite text editor, enter these lines, and save as hello.sh (note the file extension for shell scripts is .sh). Then open a Terminal window and change into the directory where the script was saved. For example:
| Code Block |
|---|
cd /Desktop |
The script can be run, with or without command line arguments, by explicitly invoking bash as follows:
| Code Block |
|---|
username$ bash hello.sh
-------------------
Hello, Shell World!
-------------------
username$ bash hello.sh Goddess
-------------------
Hello, Goddess!
-------------------
|
There is a shortcut, though, since we have the line at the top of this file that names the program that should run it. We should be able to run it just like this (where ./ means current directory), but there's a complication:
| Code Block |
|---|
username$ ./hello.sh
-bash: ./hello.sh: Permission denied
|
Welcome to the world of Unix permissions! The script file must be marked executable for this to work. To see what the current permissions are:
| Code Block |
|---|
username$ ls -la hello.sh
-rw-rw-r-- 1 user group 122 May 18 01:16 hello.sh
|
This says that anyone can read the file, the owner (you) or anyone in your group can modify it (write permission), but no one can execute it. We use the chmod program to allow anyone to execute the script:
| Code Block |
|---|
username$ chmod +r hello.sh
username$ ls -la hello.sh
-rwxrwxr-x 1 user group 122 May 18 01:16 hello.sh
|
Now hello.sh can be invoked directly:
| Code Block |
|---|
username$ ./hello.sh "Expert scripter" -------------------" echo "Hello, ShellExpert Worldscripter!" echo "-------------------" |
Open your favorite text editor, enter these lines, and save as test.sh (note the file extension for shell scripts is .sh). Using cd command, go to the directory where test.sh is. Then, execute the script by entering './test.sh'Note that when we supplied the text "Expert scripter", we put it in quotes, which group the two words into one argument to the script. Without the quotes, the word "Expert" would be seen by the script as argument 1 and "scripter" would be seen as argument 2 (which our script ignores).
Exercise 2
You already generated reference file. Now, you want to do the following task in order.
...