当前位置:网站首页>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 20This 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-a6785587b8f92 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边栏推荐
- [combinatorics] dislocation problem (recursive formula | general term formula | derivation process)*
- PHP determines which constellation it belongs to today
- leetcode:11. 盛最多水的容器【雙指針 + 貪心 + 去除最短板】
- 硬盘监控和分析工具:Smartctl
- 企业级自定义表单引擎解决方案(十二)--表单规则引擎2
- php-fpm的max_chindren的一些误区
- How to analyze the rising and falling rules of London gold trend chart
- 虚拟机和开发板互Ping问题
- 2022.02.11
- FBI 警告:有人利用 AI 换脸冒充他人身份进行远程面试
猜你喜欢

Sensor 调试流程

After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people

Computer graduation design PHP makeup sales Beauty shopping mall

235. 二叉搜索树的最近公共祖先【lca模板 + 找路径相同】

2022-2028 global solid phase extraction column industry research and trend analysis report

An academic paper sharing and approval system based on PHP for computer graduation design

Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)

FBI 警告:有人利用 AI 换脸冒充他人身份进行远程面试

Prototype inheritance..

G1 garbage collector of garbage collector
随机推荐
Golang string (string) and byte array ([]byte) are converted to each other
Computer graduation design PHP sports goods online sales system website
MySQL duplicate check
Torch learning notes (2) -- 11 common operation modes of tensor
[combinatorics] generating function (positive integer splitting | repeated ordered splitting | non repeated ordered splitting | proof of the number of repeated ordered splitting schemes)
企业级自定义表单引擎解决方案(十二)--表单规则引擎2
English grammar_ Adjective / adverb Level 3 - multiple expression
组策略中开机脚本与登录脚本所使用的用户身份
leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】
Recommend a simple browser tab
Transformer T5 model read slowly
PHP determines which constellation it belongs to today
After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
[untitled]
Chisel tutorial - 06 Phased summary: implement an FIR filter (chisel implements 4-bit FIR filter and parameterized FIR filter)
How does GCN use large convolution instead of small convolution? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
Mature port AI ceaspectus leads the world in the application of AI in terminals, CIMC Feitong advanced products go global, smart terminals, intelligent ports, intelligent terminals
How to read the source code [debug and observe the source code]
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
2022-2028 global copper foil (thickness 12 μ M) industry research and trend analysis report