MLUG Bash Scripting Workshop 25/04/08 | ||
---|---|---|
Prev | Index | Next |
I will have to start using Bash built-in commands. In order to take user input and turn it into something I can use in my script I need to use read.
In order for you to understand what I'm going to do with the basic contovob script I will have to explain the Bash built-in command read and how to assign user input to a variable in a script.
First, the explanations and then a script for you to play with!
Linux in a Nutshell states that read will "read one line of standard input and assign each word to a corresponding variable.... If only one variable is specified the entire line will be assigned to that variable".
Creating variables is also refered to as declaring variables. It can be done in a script like this
myvariable=something
If I were to use read to declare variables, I would do it as below. Read is implied by the way it is used in the snippet below. The first string read ($1) will be assigned to firstvariable and the second string read ($2) is is assigned to secondvariable.
firstvariable=$1 secondvariable=$2
The dollar sign " $ " is reserved in Bash for use with variables. The string firstvariable is just a string until it is assigned a value and Bash won't recognise it as representing a value unless it has a dollar sign in front of it.
Before we have a play with an example script there is another Bash built-in command I want discuss.
Linux in a Nutshell states that "echo" will "Write a string to standard output, terminated by a newline". This means that:
In example01 below echois used to prompt the user to enter his/her first name and surname.
Echo is also used in example01 to execute a command by enclosing the command, date inside two back-quotes like this " `date` ".
To see how all this works take a look at example01 below.
#!/bin/bash # example01 # Echo exits with a newline so lets newline ( hit enter) twice echo echo # First get some names echo "Enter your first name and surname." # Secondly create two variables from the names entered first_name=$1 second_name=$2 echo # Let's get some time and date info echo "It is now `date`" echo # Now let's echo the other variables to standard output echo "My name is $first_name $second_name" echo # end of script
Go ahead and have a play with this script.
If you tried running example_01 without entering names you would have found out that it won't give you any names if you don't give it any names.
This would be a problem with our contovob script on the previous page if a user forgot to enter the file names for the input and output videos.
However, We can use two other Bash built-ins, " test " and " if " to check and see that the user had entered the required information.