当前位置:网站首页>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边栏推荐
- [untitled]
- Sensor 调试流程
- How to read the source code [debug and observe the source code]
- Read the paper glodyne global topology preserving dynamic network embedding
- Common PostgreSQL commands
- NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
- shell 脚本中关于用户输入参数的处理
- Computer graduation design PHP sports goods online sales system website
- SSH 远程执行命令简介
- Okaleido, a multimedia NFT aggregation platform, is about to go online, and a new NFT era may come
猜你喜欢

What London Silver Trading software supports multiple languages

2022-2028 global scar care product industry research and trend analysis report

Computer graduation design PHP sports goods online sales system website

Read the paper glodyne global topology preserving dynamic network embedding

Sensor 调试流程

Chisel tutorial - 06 Phased summary: implement an FIR filter (chisel implements 4-bit FIR filter and parameterized FIR filter)

Getting started with JDBC

Sensor debugging process

Transformer T5 model read slowly

2022-2028 global aircraft head up display (HUD) industry research and trend analysis report
随机推荐
多媒体NFT聚合平台OKALEIDO即将上线,全新的NFT时代或将来临
Transformer T5 model read slowly
Recommend a simple browser tab
leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】
简述服务量化分析体系
[combinatorics] generating function (positive integer splitting | unordered | ordered | allowed repetition | not allowed repetition | unordered not repeated splitting | unordered repeated splitting)
知其然,而知其所以然,JS 对象创建与继承【汇总梳理】
2022-2028 global marking ink industry research and trend analysis report
PHP determines which constellation it belongs to today
Bidding procurement scheme management of Oracle project management system
Naoqi robot summary 27
[Godot] add menu button
English语法_名词 - 分类
webcodecs
JS_ Array_ sort
Computer graduation design PHP campus address book telephone number inquiry system
Raft 日志复制
Zhengda futures news: soaring oil prices may continue to push up global inflation
English語法_名詞 - 分類
[leetcode周赛]第300场——6110. 网格图中递增路径的数目-较难