1. Command Line parameter input
Among the methods of passing input data to a script, the basic method is to directly pass the input data to the command line. You can pass it directly to the command line as shown below.
$./test 10 20
read parameter
Bash Shell allocates a special variable called positional parameter to process the data input on the command line as above. This variable can be assigned from $0 to $9, where the name of the script file is stored in number 0, and the values entered in the command line sequentially from number 1 are stored.
Let's make an example
#!/bin/bash
#Get a single data input from the command line.
factorial=1
for (( number = 1; number ‹= $1 ; number++ )) ==> 명령어로 입력된 데이터를 $1에 할당.
do
factorial=$[ $factorial * $number ]
done
echo The factorial of $1 is $factorial
$ ./test1 5
The factorial of 5 is 120
$
Example of receiving two commands as input
#!/bin/bash
#Get two data inputs
total=$[ $1 * $2 ]
echo The first paramerer is $1.
echo The second parameter is $2.
echo The total value is $total.
$ ./test2 2 5
The first paramerer is 2.
The second parameter is 5.
The total value is 10.
$
Strings can also be entered and stored on the command line in the same variables as above. However, note that the shell regards data separation as a space, so when entering a string with a space, you must enclose the string using double quotation marks or quotation marks
When writing a script, there are cases where the variable needs more than $9 mentioned above. In that case, you can use ${10} as follows
#!/bin/bash
#How to handle a lot of input data
total=$[ ${10} * ${11} ]
echo The tenth parameter is ${10}
echo The eleventh parameter is ${11}
echo The total is $total
$ ./test4 1 2 3 4 5 6 7 8 9 10 11 12
The tenth parameter is 10
The eleventh parameter is 11
The total is 110
$
read program name
Use $0 to receive the program name as a variable on the command line.
#! /bin/bash
echo excuted command is: $0
$ ./test1
excuted command is: ./test1
$ /home/hyowon/test1
excuted command is: /home/hyowon/test1
$
Sometimes you may want to save only the script name. In this case, you can use the basename command to save only the actual script file name even if the path is input on the command line. Let's fix the example above.
#! /bin/bash
#
name=`basename $0`
echo excuted command is: $name
excute this script
$ ./test1
excuted command is: test1
$ /home/hyowon/test1
excuted command is: test1
$
So let's write a script for addition and subtraction using the script name..
#! /bin/bash
#Script example using script name
name=`basename $0`
if [ $name = "plus" ]
then
total=$[ $1 + $2 ]
elif [ $name = "mul" ]
then
total=$[ $1 * $2 ]
fi
echo The result is $total
#
Then, by copying this script, we will create two files with script names plus and mul.
$ cp test2 plus
$ cp test2 mul
Then, let's execute each input value differently on the command line.
$ ./plus 3 5
The result is 8
$ ./mul 10 32
The result is 320
However, if it is not a script I made, I don't know how many data I have to put in. For this you can write a script like this with test condition
#! /bin/bash
# Checking data input
if [ -n "$1" ] ==> If you have the first data
then
echo Hello $1, glad to meet you. ==>excute this statement and if not
else
echo "Sorry, you didn’t identify yourself." ==> excute this statement
fi
#
excute this then
$ ./test3
Sorry, you didn’t identify yourself.
$ ./test3 10
Hello 10, glad to meet you.
$ ./test3 juliet
Hello juliet, glad to meet you.
2. Special Variable Parameters
Counting parameter can count the number of input data on the command input line. The variable used for this is the $# variable. Let's take a look at the example below.
#! /bin/bash
# Script using the number of input data
if [ $# -ne 2 ]
then
echo usage: test4 a b
else
total=$[ $1 + $2 ]
echo total is $total
fi
#
So let's run it.
$ ./test4
usage: test4 a b
$ ./test4 3
usage: test4 a b
$ ./test4 3 4 5
usage: test#! /bin/bash
$ ./test4 3 4
total is 7
The way to select the last value among multiple input data is to use the variable !#. Let's look at an example below.
#! /bin/bash
# Using the last variable specified
values=$#
echo inputted valuses are $values
echo last values\'s is ${!#}
#
If you run it
$ ./test5 10 20 30 100 400
inputted valuses are 5
The values's is 400
$
Storing parameter values entered on the command line at once.
Multiple input values entered on the command line can be stored in one variable. The variables are $* and $@. $* saves all parameters input on the command line in the form of a single string, and $@ saves the data input on the command line by separating them based on space. To illustrate the difference, let's take a look at the example below.
.
#! /bin/bash
#Distinguish the difference between $* and $@
count=1
for values in "$*"
do
echo "$* parameter #$count = $values"
done
count=1
for values in "$@"
do
echo "\$@ parameter #$count = $values"
count=$[ $count + 1 ]
done
Then if you run it
$ ./test6 park kim kang choi chun ha
park kim kang choi chun ha parameter #1 = park kim kang choi chun ha
$@ parameter #1 = park
$@ parameter #2 = kim
$@ parameter #3 = kang
$@ parameter #4 = choi
$@ parameter #5 = chun
$@ parameter #6 = ha
$
As you can see above, $* treats all input data as a single character, and $@ stores each separately.
Moving input data
In the bash shell, input data can be moved to a desired location, and the command used at this time is shift. The default behavior of shift is to pull the variable values forward one by one. That is, the variable value of $3 is $2, the value of $2 is $1, and the value of $1 is discarded. This shift command is useful when you don't know how much input data is.
#! /bin/bash
# Using the shift command
count=1;
while [ -n "$1" ] ==> When there is the first data to be input, the do statement is executed
do
echo "parameter #$count = $1" ==>Print the value of the #count variable
count=$[ $count +1 ] ==> increment the number of count by one
shift ==> move data
done
excute this
$ ./test7 park kang kim choi chun ha ra
parameter #1 = park
parameter #2 = kang
parameter #3 = kim
parameter #4 = choi
parameter #5 = chun
parameter #6 = ha
parameter #7 = ra
$
Move data to a specific location with shift command
The example below is an example of moving data to a specific location using shift.
#! /bin/bash
# moving data to a specific location
echo "original data is: $*"
shift 2 ==> Pull the input data 2 spaces.
echo "shifted data is: $1"
excute this, then
$ ./test8 park kim kang chun ha ra im
original data is: park kim kang chun ha ra im
shifted data is: kang
3, use with options
Optional on the command line and more useful when used together. Let's look at 3 ways to use them with options.
Find options
This is an example of processing one option.
.
#! /bin/bash
#Example of processing one option
while [ -n "$1" ]
do
case "$1" in
-a) echo "found -a option";;
-b) echo "found -b option";;
-c) echo "found -c option";;
*) echo "$1 is not an option";;
esac
shift
done
excute this, then
$ ./test9 -a -b -c -d -e
found -a option
found -b option
found -c option
-d is not an option
-e is not an option
$
Separating options from parameters
In Linux Shell, there is a special character that separates the data input from the command input line where the option ends and the data starts. It is a double dash (--). When Shell encounters a double dash, it treats it as data after that. Let's look at the example below.
#! /bin/bash
#Using double dash
while [ -n "$1" ] ==> Repeat while there is data the first time it is input
do
case "$1" in
-a) echo "found -a option";; ==>Execute if the value of $1 is -a
-b) echo "found -b option";;
-c) echo "found -c option";;
--) shift
==> When a double dash is encountered, exit the for statement with break and proceed
from count.
bresk;;
*) echo "$1 is not an option";;
esac
shift
done
count=1
for values in $@
do
echo "parameter #$count: $valuse"
count=$[ $count + 1 ]
done
excute this then
$ ./test9 -a -b -- test12 park kang ha ra
found -a option
found -b option
parameter #1:
parameter #2:
parameter #3:
parameter #4:
parameter #5:
$
Get additional data input in options
Occasionally, additional data may be entered in the options. For example, this would be the case with the -b option when the following input is received.
$ ./test1 -a -b test2 -c -d
#! /bin/bash
#Receiving data input that requires additional input
while [ -n "$1" ]
do
case "$1" in
-a) echo " find -a option";;
-b) addpara="$2"
echo "find -b option, with addparm value $addpara"
shift ;;
-c) echo "find -c option";;
--) shift
break;;
*) echo "$1 i s not an option";;
esac
shift
done
coung=1;
for addpara in "$@"
do
echo "parameter #$count: $addpara"
count=$[ $count + 1 ]
done
If you run it, it saves the data after the -b option as shown below and prints it.
$ ./test1 -a -b test2 -c -b test3 -c -d
find -a option
find -b option, with addparm value test2
find -c option
find -b option, with addparm value test3
find -c option
-d is not an option
$
Using the getopt command
Options are sometimes entered in combination as input on the command line. For example, like ls -al, there are many cases where multiple options are attached. In this case, it is not processed in the above script. In this case, a useful command is getopt . The syntax for using the command is as follows.
$getopt option optstring parameter
If you look at the example to use, first, the options to be used for option are listed and separated by colons. You just need to define the options and parameters to be used in optstring. If you run the command below, a, b, c, and d are used as option values. You can see that the b option has one parameter after it, and -cd separates them with -c -d, and processes the two parameters that follow after inserting --.
$ getopt ab:cd -a -b value -cd value2 value3
-a -b value -c -d -- value2 value3
h$
If you input an option value that is not declared in the option part into the optstring value, an error message appears about the not entered option. If you want to ignore this, use the -q option.
$ getopt ab:cd -a -b value -cde value2 value3
getopt: invalid option -- 'e'
-a -b value -c -d -- value2 value3
$ getopt -q ab:cd -a -b value -cde value2 value3
-a -b 'value' -c -d -- 'value2' 'value3'
Using the getopt command in a script
To change the current option and parameter values to the output format of the getopt command, if you change the double-dash (--) variable to getopt in the set command, the options and parameters input to the command are processed in the getopt command format. Let's add a line to the test1 script used above to convert it to the getopt format using the set command.
#! /bin/bash
#Receiving data input that requires additional input
set -- `getopt -q ab:c "$@"`
while [ -n "$1" ]
do
case "$1" in
-a) echo " find -a option";;
-b) addpara="$2"
echo "find -b option, with addparm value $addpara"
shift ;;
-c) echo "find -c option";;
--) shift
break;;
*) echo "$1 is not an option";;
esac
shift
done
coung=1;
for addpara in "$@"
do
echo "parameter #$count: $addpara"
count=$[ $count + 1 ]
done
Then, let's try to enter the command option by attaching it.
$./test1 -ac
find -a option
find -c option
$ ./test1 -a -b value1 -cd value2 value2 value3
find -a option
find -b option, with addparm value 'value1'
find -c option
parameter #: 'value2'
parameter #1: 'value2'
parameter #2: 'value3'
$
Using the getopts command
getopt produces one output for every processed option and parameter it finds, whereas the getopts command processes the parameters sequentially in an existing shell.
The command syntax is as follows.
$getopts optstring variable
Lists valid option characters in optstring. And if these options require parameter values, separate them with colons. And like the -q option in the getopt command, start with a colon to eliminate the error message.
getopts uses two environment variables, one of which is the OPTARG variable, and this variable stores values used as parameters for options. The OPTIND variable stores the position at which getopts left in the parameter list.
After processing using this variable value, it returns to the last position and processes the next parameter. Let's take a look at the example below
#!/bin/bash
# processing options and parameters with getopts
while getopts :ab:cd opt
do
case "$opt" in
a) echo "Found the -a option" ;;
b) echo "Found the -b option, with value $OPTARG";;
=>Save the parameter value of the option b
c) echo "Found the -c option";;
d) echo "Found the -d option";;
*) echo "Unknown option: $opt";;
esac
done
shift $[ $OPTIND - 1 ] ==> OPTIND(getopts의 현 위치)를 처음으로 돌립니다.
count=1
for param in "$@"
do
echo "Parameter $count: $param"
count=$[ $count + 1 ]
done
If you run it
$ ./test20 -a -b test1 -d test2 test3 test4
Found the -a option
Found the -b option, with value test1
Found the -d option
Parameter 1: test2
Parameter 2: test3
Parameter 3: test4
$
4. Standard options.
Please refer to the table below for options standardized in Linux
사진 설명을 입력하세요.
5. Get user data input
When writing scripts, sometimes you need to wait for the user to enter data after running the script. There is a read command as a command to use in this case.
read command example
#! /bin/bash
echo -n "Enter your name: "
read name
echo "Hello $name, welcome to my program."
if you run it
$ ./test3
Enter your name: richard row
Hello park hyowon, welcome to my program.
When entering the first name above, the first and last names were separated using a space, but the output is stored in one variable and treated as a single string. Separation is possible by modifying them together. The -p parameter is used to define the message of the printed prompt.
#! /bin/bash
#read command example
read -p "Enter you name" first last
==> The first and last names are stored separately in first and last respectively.
echo "Hello $name, welcome to my program."
If you do not designate a variable to save data in the read command, the value input to the REPLY variable among environment variables is saved.
#!/bin/bash
# testing the REPLY environment variable
read -p "Enter a number: "
factorial=1
for (( count=1; count ‹= $REPLY; count++ ))
do
factorial=$[ $factorial * $count ]
done
echo "The factorial of $REPLY is $factorial"
$ ./test24
Enter a number: 5
The factorial of 5 is 120
$
Handling read command timeout
The -t option can specify the amount of time to wait for the user to input data after executing the read command. The value of -t can be specified in seconds. If timeout occurs, the read command returns a non-zero exit code.
Example code (when the script is executed and no input is made for 5 seconds)
#! /bin/bash
# Example of using the -t option with read
if read -t 5 -p "please enter you name:" name
then
echo "Hello $name, welcome to my world"
else
echo
echo "Sorry. too sloe!"
fi
If you run the avobe script
$ ./test4
please enter you name:
Sorry. too sloe!
$
Below is an example of receiving yes or no input from the user.
#!/bin/bash
# getting just one character of input
read -n1 -p "Do you want to continue [Y/N]? " answer
==> -n1 allows input of only one character.
case $answer in
Y | y) echo
echo "fine, continue on...";;
N | n) echo
echo OK, goodbye
exit;;
esac
echo "This is the end of the script"
$ ./test26
Do you want to continue [Y/N]? Y
fine, continue on...
This is the end of the script
$ ./test26
Do you want to continue [Y/N]? n
OK, goodbye
$
Do not display input data
Among the data input from the user through the read command, there are cases where you do not want to display passwords or sensitive data on the monitor. In this case, you can suppress that data by using the -s option.
For example, if you use it as read -s -p "Enter your password:" pass , the data entered by the user will not be visible on the monitor.
read from file
When data is read from a file using the read command, the read command reads each line of the file, and when all data is read, the read command returns an exit code as non zero.
#! /bin/bash
# Reading data from a file using the read command
count=1
cat test7 | while read line
do
echo "Line $count: $line"
count=$[ $count + 1 ]
done
echo "Finished processing the file"
if you excute this
$ ./test5
Line 1: #! /bin/bash
Line 2: yeah this is test script for read
Line 3: is it work or not
Line 4: are you interesting to make scripting
Line 5: 0 5 dkjfks dkjreijfa
Line 6: jkdmnvk dkjiwjkfsj kdjfkjca
Line 7: sjdkfjkzxg
Line 8:
Finished processing the file
$
'Shell Script' 카테고리의 다른 글
11 Script Control (0) | 2022.08.15 |
---|---|
10 Data Expression (2) | 2022.08.13 |
8 Detailed Structed Shell Command (1) | 2022.08.12 |
7 Structured Command (5) | 2022.08.11 |
6. Basic Shell Script writing (3) | 2022.08.11 |