We can provide arguments to a shell script from the command line. Inside the script
The command "who" lists all the users that are logged in.
Ex: "whos_logged_in.sh"
#illustrate an argument
who | egrep "$1"
After making the script executable we can run it with the command:
./whos_logged_in.sh amittal
Output:
[amittal@hills Arguments]$ ./whos_logged_in.sh amittal
amittal pts/2 2018-11-16 08:19 (64.125.46.186)
Another example involves compiling a Java program.
Ex: "run1.sh"
rm $1.class
javac $1.java
java $1
[amittal@hills Arguments]$ ./run1.sh hello
rm: cannot remove ‘hello.class’: No such file or directory
Hello World
File: "hello.java"
public class hello
{
public static void main(String args[] )
{
System.out.println("Hello World" ) ;
}
}
We want to remove the ".class" file so that if the Java program has a compilation run then the last line "java" will not run the old class file. If we don't have a class file to begin with then "rm" gives us a warning. We can remove the warning with the "-f" option for "rm" .
File: run2.sh
rm -f $1.class
javac $1.java
java $1
We can also redirect the error stream to a special path called "/dev/null/" . This is a path that will discard any streams redirected to it.
,./run2.sh 2>/dev/null
We have 3 standard stream: input, output and error . These are reoresented by the numbers 0, 1 and 2 . The "/dev/null"
We can use "$#" variable to count the number of arguments that were provided.
File: arg1.sh
if [ $# -ne 3 ]
then
echo $# "arguments typed"
echo "Please input 3 arguments:"
exit 1
fi
echo "Number of arguments: $#
cat "$1" "$2" > "$3"
The above program uses the "$#" symbol to check the arguments that were given . If we run the program as:
[amittal@hills number_of_arguments]$ ./arg1.sh first second third
Number of arguments: 3
The symbol "${n}" can be used to access arguments whose level is greater than 9 . As an example if we want to access the 10th argument we can write "${10}" .
Printing all the arguments
We can print all the arguments using the "$*" syntax.
The "shift" command.
The shift command will reduce the value of "$#" by one and the value of "$3" will be stored into "$2" .
Ex:
echo $# $*
shift
echo $# $*
Output:
[amittal@hills Arguments]$ ./tshift.sh a b c
3 a b c
2 b c
Initially the number of arguments is printed as 3 and the variables are printed as "a", "b" and "c" .
We then execute a "shift" command and the "$#" becomes now 2 and the arguments are shifted left to become "b and c" .
Exercise
Write a shell script called "c1.sh" . Ask a user to enter 3 parameters. If the user does not enter 3 parameters then print an error message and exit the program.
Take the first 2 arguments to be the names of files and concatenate them using the "cat" command to place the output in the third argument.
//Compiling a java program
//Creating a blank template