Implementation of wonderful characters in shell

Time:2020-9-25

Among the programming languages I’ve been exposed to, the two most wonderful ones are JavaScript and shell. Because they have too much syntax sugar and special characters, they can always catch you off guard, and their programming habits are quite different from those of Java and python. In a word, don’t despise them just because they are scripting languages, or you’ll be knocked out of your wits.

Compared with these two wonderful flowers, shell’s wonderful work is that there are many special symbols and many Sao operations. For example, you think. This is a point. In fact, it means more than one point.

The following content is a special character in a shell that I sorted out according to the online information and usual use experience. If you think it’s useful, please like it.

; single semicolon, usually used as a command separator. You can put two commands on the same line. For example: echo hello; echo there, but try not to write a script like this.

;; double semicolon used as the terminator of a case conditional statement. For example:


case "$variable" in
 abc) echo "$variable = abc" ;;
 xyz) echo "$variable = xyz" ;;
esac

%A percent sign, used to indicate remainder operations, is also used in regular expressions.

~The wavy line, which represents the home directory, is equivalent to $home. Such as CD~

~+Represents the current working directory, equivalent to $PWD.

~-Represents the last working directory, equivalent to.

|Pipeline identifier, the output of the previous command as the input of the next command, is often used, there is nothing to say.

>|Force redirection. Force an existing file to be rewritten.

||Represents logic or operation.

&Let commands run in the background, such as command & which is generally used to start background process services.

&&Represents logic and operation.

*Asterisk, mainly used for wildcard matching, is also used for multiplication expressions.

\It is mainly used to escape special characters. For example, if you want to escape double quotation marks, you can echo “output”.

/File path separator, such as / opt / APP / projects /. It’s also used as a division expression.

Dot. This symbol has more functions. First, it can be equivalent to the source command. It can also be used as a file name. At the beginning of the file name, it means that the file is a hidden file. It can also represent the current directory, such as copying a file to the current directory CP / opt / APP / a.md. If they are two consecutive dots, they represent the upper level directory, such as CD.
Finally, the period is also a metacharacter of a regular expression.

“Double quotation marks. The variables in double quotation marks are usually resolved into the content of assignment. such as


 name=frank
 echo "hello $name" # hello frank

‘single quotation marks. Variables in single quotation marks will not be parsed. For example


 name=frank
 echo 'hello $name' #hello $name

The back quotation mark (the one under the ESC key) should be distinguished from the single quotation mark. The contents in the back quotation marks are executed as instructions, and the results of the execution are assigned to variables. For example:

file=`ls ~`
Echo $file all the files in the home directory.

! exclamation mark, generally used to reverse. For example! = means unequal. If the operation is executed in the terminal, it can indicate the historical instruction, such as! – 3, which will output the instruction you just entered. However, it is not supported in scripts.

**Double star, which means exponentiation in arithmetic operation. such as


let "a=3**2"
echo $a #9

? question mark for conditional testing; also used as a ternary operator. It is also a regular expression metacharacter.

The $Dollar sign refers to the content of a variable, such as echo $path; of course, it is also the metacharacter of regular expressions.

The ${} parameter replacement. Used to represent the value of a variable in a string. such as


name=frank
echo "hello ${name}" #hello frank

The two special characters $*, [email protected] are used to get all the parameters passed to the script. When they are surrounded by double quotation marks, “$*” treats all parameters as one piece of data. And “[email protected]” still treats each parameter as a piece of data, independent of each other.

$#, represents the number of parameters.

$? Returns the exit status code of the latest command or script. If it is executed correctly, it will return 0, otherwise it will return non-0.

The double dollar sign returns the process number of the current script.

() parentheses, command groups, a set of commands enclosed in parentheses represent a command group and run as a subshell. At the same time, the variables in parentheses are similar to local variables and cannot be accessed externally. such as


a=123
( a=321; )
echo "a = $a" # a = 123

It can also be used for array initialization. for example


arr=(ele1 ele2 ele3)
echo ${arr[1]} # ele2

[XXX, YYY, zzz} some people call it curly bracket extension. I will give a few examples, and you will understand. Note that no spaces are allowed.

echo {a,b,c}-{d,e,f} # a-d a-e a-f b-d b-e b-f c-d c-e c-f
cat {file1,file2,file3} > merge_ File ා enter the contents of the three files into merge_ file
CP file. {TXT, backup} copy file.txt become file.backup

{a.. Z} is similar to the above.


echo {a..z} # a b c d e f g h i j k l m n o p q r s t u v w x y z
echo {0..3} # 0 1 2 3

The {} curly brackets, which represent code blocks, are also used to represent anonymous functions. It can also be used in combination with the redirection character. For example:


fileline=~/a.txt
{
 read line1
 read line2
 } < $fileline
 echo $line1
 echo $lien2

The first two lines of a.txt are assigned to the variables Line1 and line2;

In xargs – I, the operation can also be used as a place holder for the text to mark the position of the output text.

For example, LS *. TXT | xargs – I – t CP {}}}. Bak copies all the txt files and names them txt.bak

The first name represents the path. It is usually used with the find command. For example, find. – name “*. Sh” – exec RM {} \; find all sh scripts and delete them. Note the space between {} and . Semicolons must exist.

The bracket is used to write the judgment expression inside. It can also be used as an array. Of course, it’s also a regular expression metacharacter.

[[]] double bracket, also used to write judgment expression inside, is more flexible than the above but bracket.

It is not recommended to use $[] to calculate integer expressions. for example


a=3;
b=7;
echo $[$a+$b] # 10

(()) double parentheses, calculating integer expression, recommended. as


a = 23
(( a++ ))
echo "a (after a++) = $a" # 24

>,, & >, >, >, and > > are redirection characters, which are illustrated by examples.
Cat ~ / a.txt > a.log to output the contents of the file a.txt to the file a.log. If the file exists, it will be overwritten;
Command & > file name to redirect the standard output (stdout) and standard error (stderr) of command to the file filename, which is generally used to start the process script;
Command > & 2 redirect stdout of command to stderr;
Cat ~ / a.txt > > a.log input the output of a.txt into the file a.log by appending. If the file does not exist, it will be created.

-Short horizontal line, which can be used for parameter selection, such as LS – al. It can also represent the previous working directory, such as CD -. It’s also a mathematical operator, of course, used to represent subtraction operations.

=Equal sign, mathematical operator, assignment operation. for example


a=28
echo $a

It can also be used to indicate a comparison operation. For example, if [“$a” = $B “] note that there should be spaces on the left and right sides of the equal sign.

#A pound sign, usually used in front of a comment statement, indicates that the statement is a comment. It is also a metacharacter of a regular expression.

be careful:

The first line of the script ා / bin / Bash is not used as a comment, and those after double or single quotation marks and escape characters are not used as annotations. for example


echo "The # here does not begin a comment."
 echo 'The # here does not begin a comment.'
 echo The \# here does not begin a comment.

The operation can be converted to base, for example


 echo $((2#101)) #5
 echo $((8#101)) #65
 echo $((10#101)) #101

, comma, used to connect a series of mathematical expressions that are evaluated, but only the last evaluation result is returned. For example:


# Set "a = 9" and "t2 = 15 / 3"
let "t2 = ((a = 9, 15 / 3))"

It can also be used to concatenate strings, such as echo {a, B} / test to output a / test, B / test

Operation is used in variable references to indicate that the first letter is lowercase. If two commas are used, it means all lowercase. for example


 a="AFrank"
 echo ${a,} #aFrank
 echo ${a,,} #afrank

+A mathematical operator that represents the addition operation. It is also a regular expression metacharacter.

The operation is used to set the value of a variable. How to use ${parameter + Alt_ Value} if the variable parameter has a value set, ALT is used_ Value, otherwise null characters are used.

For example, feel it


#param1 not set
a=${param1+xyz}
echo "a = $a"  # a =

#parma2 set null
param2=
a=${param2+xyz}
echo "a = $a"  # a = xyz

param3=123
a=${param3+xyz}
echo "a = $a"  # a = xyz

Note that there are differences when used with colons. For example, continue to feel it


a=${param4:+xyz}
echo "a = $a"  # a =

param5=
a=${param5:+xyz}
echo "a = $a"  # a =

#Different result from a=${param5+xyz}
param6=123
a=${param6:+xyz}
echo "a = $a"  # a = xyz

^For regular expressions.

Operation is used for case conversion. Look at the example below.


var=hellFrank
echo ${var^}   # HelloFrank
echo ${var^^}   # HELLOFRANK

The double less than sign is called here doc. It is generally used to provide multiple lines of input to a command. such as


tr a-z A-Z <<EOF
 > one
 > two
 > three
 > EOF

Output:

ONE  TWO  THREE

By default, the variables in here doc will be replaced. such as


cat << EOF
 > Working dir $PWD
 > EOF

Output: working dir / home / Frank

If you place double or single quotation marks on the here doc identifier, variable substitution is prohibited. such as


cat << "EOF"
 > Working dir $PWD
 > EOF

Output: working dir $PWD

Operation

Add – after < < to ignore tab white space. such as


tr a-z A-Z <<-EOF
 > one
 > two
 > three
 > EOF 

Output: one two there

The three less than signs are called here string, variants of here doc. More flexible than here doc. for example
tr a-z A-Z <<<"Yes it is a string" # YES IT IS A STRING
name=frank
#Variables are parsed in double quotation marks
tr a-z A-Z <<<"Yes i'm $name" # YES I'M FRANK
#Variables are not parsed in single quotation marks
tr a-z A-Z <<<'Yes i\'m $name' # YES I'M $NAME

: colon, which means empty, does nothing, but has a return value of 0 (i.e. true)
For example::; echo $? Outputs 0. $? Means to return the status of the previous instruction.
This feature can be used as an infinite loop condition of while or as a place holder for an if branch.

such as


while : #same as while true
do
 operation-1
 operation-2
 ...
 operation-n
done

perhaps


if condition
then : # Do nothing and branch ahead
else  # Or else ...
 take-some-action
fi

In addition, it can be used in combination with the redirection symbol to empty the file content, but does not change the file permissions. If it does not exist, it will be automatically created.


: > data.xxx # File "data.xxx" now empty.

Equivalent to cat / dev / null > data.xxx If you redirect by appending, no changes are made to the file. Also, if the file does not exist, a new one will be created. For example: > > data.xxx 。

Note that this can only be used in ordinary files, not in pipes, symbolic links and other special files;

You can also be used as a field separator. For example, in the environment variable $path or passwd, colons exist as domain separators; for example
usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/games

The default value is set by the operation. If param is not set, the default value is used, for example


parma=frank
echo ${param:=default} #frank
echo ${test:=default} #default

You can also use a colon as a function name, but this will change the original meaning of a colon, so don’t do that.


:()
{
 echo "The name of this function is colon"
}

Reference for the above contents:( http://tldp.org/LDP/abs/html/special-chars.html )I hope it will be helpful to your study, and I hope you can support developeppaer more.