Simple use of shell
Recently I found that shell scripts are simply a Swiss army knife in daily work. In many scenarios, shell scripts can achieve common simple needs. I haven’t learned shell much before, so I took the opportunity to summarize the grammar and common usage of shells, so that it is convenient to review and review at any time in the future!
1. Overview
shebang
In fact, the beginning of the shell is not difficult, the first line is as follows:
#!/bin/bash
Shebang
Comments
The shell's comments start with # (this is similar to python)
variable
Variable definition:
var_test1="hello"
Note that when defining and assigning = there cannot be spaces on both sides, and $ cannot be added before the variable name!
Variable usage:
echo $var_test1
or
echo ${var_test1}
or:
str1="${var_test1} world"
The variable after adding the dollar sign will be replaced with its value. Note that the single quotes will not be replaced
The command execution result is assigned to a variable:
lines=`wc -l ` # Here lines are assigned as the number of lines lines="$(wc -l )" # Single apostrophes cannot be nested, this can be included
Format variables:
echo 23 | awk {printf("%05d", $0);} # 00023
String intercept:
${var_test1:1:3}
"ell", that is, take 3 characters from index 1
Output
The output in the shell can be directly used to use echo
echo "hello word"
Equivalent to
echo hello word
enter:
- echo "What's your name?"
- read Name # No need to declare new variables here
- echo Hello, $Name!
Multiple statement combination
&&
: Meets the short circuit principle, that is, the second command will not be executed when the first command returns failed
||
: Meets the short circuit principle, that is, the second command will not be executed when the first command returns successfully
;
: No short circuit, no matter whether the first command returns successfully or not, the second command will be executed
echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" echo "Always executed1" ; echo "Always executed2"
Channels and redirections
cmd1 | cmd2
: Channel, the output of the first command will be executed directly as the standard input of the second command
python <
: Input redirection will be read from the input instead of the standard input stream
echo "hello" >
: Output redirection, directing the output of the previous command to a file (create a new file and write it)
echo "hello" >>
: Output redirection, directing the output of the previous command to the file (append to the end of the file)
echo "hello" 2>
: Error stream redirection, directs the error stream output of the previous command to a file (create a new file and write it)
echo "hello" 2>>
: Error stream redirection, directs the error stream output of the previous command to the file (append to the end of the file)
2. Judgment
The simplest judgment logic is:
if [ condition1 ]; then statement1 elif [ condition2 ]; then statement2 else statement3 fi # Or use testif test condition1 ; then statement1 fi
Note: There must be at least one space between the two sides of the condition and []
Judgment conditions
The judgment conditions in the shell are different from <,>,==,<=,>= in other languages. So directly, there are the following common ones:
-eq equal(==) -ne 不equal(!=) -gt Greater than(\>) -lt Less than(\<) -le Less thanequal -ge Greater thanequal -z Empty string -n 非Empty string == Two characters equal != Two characters vary
Combination judgment
-a and -o or
Special usage[[ ... ]]
When comparing strings, you can use the right side as a pattern, not just a string, for example[[ hello == hell? ]]
The result is true
The &&, ||, < and > operators can exist normally in[[ ]]
The conditional judgment structure is in, but if it appears in the [ ] structure, an error will be reported. For example, you can use it directlyif [[ $a != 1 && $a <= 5 ]]
, if double brackets are not used,if [ $a -ne 1] && [ $a -le 5 ]
orif [ $a -ne 1 -a $a -le 5 ]
Document judgment
-f Determine whether the following file is -d Determine whether the following is a directory -e Determine whether the corresponding file exists afterwards -s Determine whether the file exists and is not empty
switch case
case "$Variable" in # List the strings that need to be matched 0) echo "There is a zero.";; 1) echo "There is a one.";; *) echo "It is not null.";; esac
3. Loop
for loop
# {1..3} == `seq 1 3` for Variable in {1..3} do echo "$Variable" done
Or a traditional "for loop", but two layers of brackets are required (the statements in C can be written in the brackets of the two layers):
for ((a=1; a <= 3; a++)) do echo $a done
Execute a for loop on the result of other commands:
for Output in $(ls) do cat "$Output" done
while loop
while [ condition ] do echo "loop body here..." break done
4. Command line
$# Number of command line parameters$0 Current script name $n ThenParameter values,nDesirable1,2,3... $@ All command line parameters $? The return value of the previous command
5. Other common commands
# Print the previous content in each linecut -d ',' -f 1 # Replace all 'okay' in the file with 'great', (compatible with regular expressions)sed -i 's/okay/great/g' # The shell does not support floating point division operation, floating point division can be implemented using awka=3 b=4 c=`awk 'BEGIN{printf "%.2f",('$a'/'$b')}'` # Variables in single quotes cannot be replaced,Therefore, variables need to be placed separately outside quotes
This article briefly introduces some of the usages of shells. If there is any wrong, please correct me. I just started to use shell not long ago. It is a powerful and complex language. If you have better shell information, please leave a message and learn together. Thank you!
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!