当前位置:网站首页>Processing of user input parameters in shell script
Processing of user input parameters in shell script
2022-07-03 18:42:00 【It workers】
shell The processing of user input parameters in the script
bash shell The script provides 3 Plant from User department How to get data :
Command line arguments ( Add the data after the command )
Command line options
Read input directly from the keyboard
1 Command line arguments
image shell The most basic way for scripts to pass data is to use Command line arguments .
Example :
./add.sh 10 20
This example provides the script add.sh Passed two Command line arguments (10 and 20).
1.1 Read the command line arguments
bash shell There are some special variables in , go by the name of Positional arguments (positional parameter).
The standard number of position parameters is :
$0 It's the program name ;
$1 Is the first parameter ;
$2 It's the second parameter ;
By analogy , $9 Is the ninth parameter .
${10} It's the tenth parameter …
Look at a request Factorial (factorial) Example :
$ cat temp.sh
#!/bin/bash
factorial=1
for (( i=1; i<=$1; i++)); do
factorial=$[$factorial * $i]
done
echo "the factorial of $1 is $factorial"
$ ./temp.sh 4
the factorial of 4 is 24
If shell Scripts need to be used Command line arguments , But the script does not add Command line arguments , Something could go wrong , For example, in the above example , If you run without parameters, an error will be reported :
$ ./temp.sh
./temp.sh: line 3: ((: i<=: syntax error: operand expected (error token is "<=")
the factorial of is 1
Generally, we need to check Command line arguments , Modify the above example :
$ cat temp.sh
#!/bin/bash
# Command line arguments 1 Whether the string length is zero
if [ -z "$1" ]; then
echo "usage: $0 number"
exit 0
fi
factorial=1
for (( i=1; i<=$1; i++)); do
factorial=$[$factorial * $i]
done
echo "the factorial of $1 is $factorial"
$ ./temp.sh
usage: ./temp.sh numbe
bash shell Several special variables are also provided :
$# Carried by the script when it runs Number of command line arguments ;
$* Put the... Provided on the command line All the parameters treat as A word preservation ;
[email protected] Put the... Provided on the command line All the parameters treat as Multiple independent words preservation .
Example :
$ cat temp.sh
#!/bin/bash
echo "There wre $# parameters supplied."
count=1
for param in "$*"; do
echo "\$*, Parameters $count = $param"
count=$[ $count + 1 ]
done
count=1
for param in "[email protected]"; do
echo "\[email protected], Parameters $count = $param"
count=$[ $count +1 ]
done
$ ./temp.sh miyan rosie abby
There wre 3 parameters supplied.
$*, Parameters 1 = miyan rosie abby
[email protected], Parameters 1 = miyan
[email protected], Parameters 2 = rosie
[email protected], Parameters 3 = abby
If you put "$*" Double quotation marks on "" Get rid of , $* Will output and "[email protected]" The same result .
1.2 shell parameter expansion
Here are two commonly used Parameter extension :
${variable_name:-value}: If variable_name The value of is empty , return value.
${variable_name:?msg}: If variable_name The value of is empty , return message Error and exit .
Example :
$ cat temp.sh
#!/bin/bash
name=${1:? user name cannot be empty}
password=${2:-$(uuidgen | tr '[:upper:]' '[:lower:]')}
echo "username: $name, passowrd: $password"
$ ./temp.sh
./temp.sh: line 2: 1: user name cannot be empty
$ ./temp.sh miyan
username: miyan, passowrd: e2c7956c-cd6c-4761-a323-a6785587b8f9
2 Command options
Options (option) It's following Dashes (dash -) The last single letter , It can change the behavior of commands .
Handle Options involves getopt and getopts command .
Here is a brief introduction , When you need it, come back and make it up .
3 Get user input
Even though Command line options and Parameters It's from User department An important way to get input , But sometimes scripts need to be more interactive .
For example, ask a question when the script is running , Wait for the person who runs the script to answer , bash shell This provides read command .
3.1 read command
read variable_name From standard input ( keyboard ) or In another file descriptor Accept input , After receiving the input , read Data will be stored in variables .
read Order sample :
$ cat temp.sh
#!/bin/bash
# -n, don't output the trailing newline.
echo -n "Enter you name: "
read name
echo "Hello $name"
$ ./temp.sh
Enter you name: miyan
Hello miyan
read Yes 3 Common use Options -p, -s and -t:
read -p “prompt text” variable_name: -p here stands for the prompt. Here we read the data along with some hint text .
read -s variable_name: This option -s means secret or secure whatever is used to read the sensitive data.
read -t seconds variable_name: Set up timeout Time , Unit second , Timeout returns non 0 Exit status code .
When read When reading multiple variables , Multiple variables are separated by spaces :
$ cat temp.sh
#!/bin/bash
read -p "three names: " u1 u2 u3
echo "Hello $u1, $u2, $u3 !!!"
$ ./temp.sh
three names: miyan rosie abby
Hello miyan, rosie, abby !!!
3.2 Read from file
read The command can read the data saved in the file . Every time you call read command , It will read a line of text . When there is no content in the file , read Will exit and return to non 0 Of Exit status code .
The problem is how to transmit the file data to read ?
The most common way is Use... For files cat command , Pass the result through The Conduit Direct to contain read Ordered while command .
Look at an example :
$ cat test.txt
Crazy waves
hotel california
nothing's gonna change my love for you
$ cat temp.sh
#!/bin/bash
count=1
cat test.txt | while read line; do
echo "line $count: $line"
count=$[ $count + 1 ]
done
$ ./temp.sh
line 1: Crazy waves
line 2: hotel california
line 3: nothing's gonna change my love for you
There is also an advanced way of writing , use Input redirection :
$ cat temp.sh
#!/bin/bash
count=1
while read line; do
echo "line $count: $line"
count=$[ $count + 1 ]
done < test.txt
$ ./temp.sh
line 1: Crazy waves
line 2: hotel california
line 3: nothing's gonna change my love for you
边栏推荐
- Recommend a simple browser tab
- Have you learned the correct expression posture of programmers on Valentine's day?
- 平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方
- The vscode code is automatically modified to a compliance code when it is formatted and saved
- What is the function of registering DLLs- What does registering a DLL do?
- Data analysis is popular on the Internet, and the full version of "Introduction to data science" is free to download
- Torch learning notes (1) -- 19 common ways to create tensor
- Reappearance of ASPP (atlas spatial pyramid pooling) code
- 毕业总结
- Read the paper glodyne global topology preserving dynamic network embedding
猜你喜欢
235. 二叉搜索树的最近公共祖先【lca模板 + 找路径相同】
Implementation of cqrs architecture mode under Kratos microservice framework
Pan for in-depth understanding of the attention mechanism in CV
Opencv learning notes (continuously updated)
2022-2028 global solid phase extraction column industry research and trend analysis report
Naoqi robot summary 27
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
Getting started with JDBC
2022-2028 global aircraft head up display (HUD) industry research and trend analysis report
Grammaire anglaise Nom - Classification
随机推荐
189. Rotation array
Chisel tutorial - 06 Phased summary: implement an FIR filter (chisel implements 4-bit FIR filter and parameterized FIR filter)
SQL: special update operation
Introduction to SSH Remote execution command
[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University
204. Count prime
Mysql45 lecture learning notes (II)
Class exercises
Self executing function
[combinatorics] generating function (use generating function to solve the number of solutions of indefinite equation example 2 | extended to integer solution)
[Godot] add menu button
Usage of laravel conditional array in
Software development freelancer's Road
How about the Moco model?
Database creation, addition, deletion, modification and query
SQL custom collation
Torch learning notes (2) -- 11 common operation modes of tensor
2022-2028 global marking ink industry research and trend analysis report
SSH 远程执行命令简介
How to analyze the rising and falling rules of London gold trend chart