当前位置:网站首页>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] generating function (example of using generating function to solve the number of solutions of indefinite equation)
- Torch learning notes (3) -- univariate linear regression model (self training)
- SQL custom collation
- Class exercises
- English語法_名詞 - 分類
- What London Silver Trading software supports multiple languages
- Install apache+php+mysql+phpmyadmin xampp and its error resolution
- Redis cache avalanche, penetration, breakdown
- Zhengda futures news: soaring oil prices may continue to push up global inflation
- Win 11 major updates, new features love love.
猜你喜欢

Summary and Reflection on the third week of winter vacation

leetcode:11. 盛最多水的容器【双指针 + 贪心 + 去除最短板】

Data analysis is popular on the Internet, and the full version of "Introduction to data science" is free to download

How to track the real-time trend of Bank of London

2022-2028 global lithium battery copper foil industry research and trend analysis report
![[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University](/img/52/b97c618a8f2eb29ad0ccca221bb5c1.jpg)
[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University

Web3 credential network project galaxy is better than nym?

Kratos微服务框架下实现CQRS架构模式

2022-2028 global physiotherapy clinic industry research and trend analysis report

Analysis of the reasons why enterprises build their own software development teams to use software manpower outsourcing services at the same time
随机推荐
199. Right view of binary tree - breadth search
How to analyze the rising and falling rules of London gold trend chart
12、 Service management
2022-2028 global aircraft head up display (HUD) industry research and trend analysis report
Redis cache avalanche, penetration, breakdown
[combinatorics] exponential generating function (concept of exponential generating function | permutation number exponential generating function = combinatorial number ordinary generating function | e
Graduation summary
JS_ Array_ sort
How to disable the clear button of ie10 insert text box- How can I disable the clear button that IE10 inserts into textboxes?
Torch learning notes (1) -- 19 common ways to create tensor
Typescript configuration
leetcode:11. 盛最多水的容器【双指针 + 贪心 + 去除最短板】
硬盘监控和分析工具:Smartctl
平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方
Opencv learning notes (continuously updated)
leetcode:11. 盛最多水的容器【雙指針 + 貪心 + 去除最短板】
[Godot] add menu button
Raft 日志复制
2022-2028 global sepsis treatment drug industry research and trend analysis report
Unsafe类的使用