Shell syntax and examples

Time:2021-9-21

Language introduction

Bash, a kind of UNIX shell, was written by Brian Fox for the GNU Project in 1987.
The first official version was released in 1989. It was originally planned to be used on the GNU operating system, but it can run on most UNIX like operating systems, including Linux and Mac OS X V10.4 to Mac OS Mojave,
Since MacOS Catalina, the default shell is replaced by Zsh.
–From Wikipedia

Grammar and characteristics

Bash’s command syntax is a superset of Bourne shell command syntax.
A large number of Bourne shell scripts can be executed in Bash without modification. Only those scripts that reference Bourne special variables or use Bourne’s built-in commands need to be modified.
Bash’s command syntax comes from Korn shell (KSH) and C shell (CSH), such as command line editing, command history, directory stack, $random and $PPID variables, and POSIX’s command substitution syntax: $(…).
As an interactive shell, press the tab key to automatically complete the partially entered program name, file name, variable name, etc.

When using the ‘function’ keyword, bash’s function declaration is incompatible with Bourne / Korn / POSIX scripts (Korn shell has the same problem).
However, bash also accepts Bourne / Korn / POSIX’s function declaration syntax.
Because of many differences, bash scripts rarely run in the Bourne or Korn interpreter unless they are written with the intention of maintaining compatibility.
However, with the popularity of Linux, this approach is becoming less and less. However, in POSIX mode, Bash is more POSIX compliant.

grammar

Variable definition

name="foo"

be careful,There must be no space between variable name and equal sign, this may be different from all programming languages you are familiar with.
Meanwhile, the naming of variable names must follow the following rules:

  • Naming can only use English letters, numbers and underscores. The first character cannot start with a number.
  • There can be no spaces in the middle. You can use an underscore (\).
  • Punctuation cannot be used.
  • Keywords in Bash cannot be used (you can use the help command to view reserved keywords).

Use variables

Use only the dollar sign$that will do

Print:echo $name
Print results:foo

If the dollar sign is not added, it is a string:

Print:echo name
Print results:name

Of course, curly braces can also be added on both sides of the variable:

name="foo"

echo "I am good at ${name} Script"
echo "I am good at $name Script"

//These two sentences are equivalent. The advantage of curly braces is the space

Define read-only variables

url="mo.fish"
readonly url

url="jandan.net"

An error will be reported when the value is assigned again:index.sh: line 14: url: readonly variable

Delete variable

name="foo"
url="mo.fish"

unset url
unset name

Note: read only variables cannot be deleted. An error is reported:index.sh: line 14: unset: url: cannot unset: readonly variable

After the normal variable is deleted, the print result is empty

About strings

Try to use it in the shellDouble quotation mark
Because variables are not valid in single quotes, this is a very important point

String splicing

Splice through spaces:

name="foo"
url="mo.fish"

echo $name $url

String length

add#that will do

name="foo"
echo ${#name}

String interception

Use colon:

url="mo.fish"

echo ${url:1:3}
//Printing: O.F
//First to third from 0

array

array define

The array is represented by parentheses, and the array elements are separated by the “space” symbol.

arr=($name $url)
echo ${arr[1]}

//Echo ${arr} is equal to echo ${arr [0]}“

Print all arrays

This is quite special

arr=($name $url)
echo ${arr[@]}

Get array length

Similar to string:

length=${#arr[@]}
echo $length

Process control

if else

If is somewhat different from other languages:

if [ $name=="foo" ]
then
  Echo "name is foo"
fi
//Fi means end, because unlike other languages, there is no {}

The words else and if else are written as follows:

if [ $name != "foo" ]
then
  Echo "name is foo"
else
  Echo "Non Conformance"
fi
if [ $name == "bar" ] ;then
  Echo "name is bar"
elif [ $name == "foo" ]; then
  Echo "name is foo"
else
  Echo "Non Conformance"
fi

Such use; thenIt may be more in line with our intuition

for

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

while

int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

Both for and while use only one simple example

function

definition

GrewerFn(){
    Echo "this is my first shell function!"
}

implement

Performing is a simple operation:

GrewerFn(){
    Echo "this is my first shell function!"
}

GrewerFn

Just write the function name to call

parameter

GrewerFn(){
    Echo "the first parameter is $1!"
    Echo "the second parameter is $2!"
    Echo "print all parameters [email protected]"
}

GrewerFn 1 "qwer" "zxc"

In this way, parameters can be passed

And inside$1, $2The following table can be used for such parameter processing:

Parameter processing explain
$# The number of arguments passed to the script or function
$* Displays all parameters passed to the script in a single string
$$ ID number of the current process the script is running
$! ID number of the last process running in the background
[email protected] Same as $*, but use in quotation marks and return each parameter in quotation marks.
$- Displays the current options used by the shell, with the same function as the set command.
$? Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error.

interactive

Get user input

read

The method used is simple:

read yourName
echo "you name is $yourName"

Parameters can be added later, such as
-P parameter, which allows you to specify a prompt directly on the read command line.

Read - P "enter website name:" website
    Echo "the website name you entered is $website"

Qualifying characters:

read -n1 -p "Do you want to continue [Y/N]?" answer
case $answer in
Y | y)
      echo "fine ,continue";;
N | n)
      echo "ok,good bye";;
*)
     echo "error choice";;
esac
select
PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice 1"
            ;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 3")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Quit")
            break
            ;;
        *) echo "invalid option $REPLY";;
    esac
done

Small supplement

PS1 – default prompt
PS2 — talk again
PS3 — prompt when select is used in shell script
PS4 – “set – X” is used to modify the prefix of trace output

Specific reference:https://os.51cto.com/art/2012…

other

There is also a popular expect. I won’t say much here. It needs to be downloaded. Some embedded environments don’t support it

Common scenarios

  • Automatic script on Linux: for example, I used crontab to perform scheduled tasks, read and modify files. I also used it in a previous article:https://segmentfault.com/a/11…
  • Login scripts and so on, you can omit a lot of troublesome processes

    Of course, compared with other languages, this can be done. The advantage of shell lies in its native support
  • Initialize the environment. Use the script to initialize the entire linux environment with one click. If you have contacted cli, you should know its role

epilogue

As the official language of Linux, shell comes with many functions and provides us with a lot of convenience
When there is no environment, you can also run it directly. Learning this language can help you develop your skills in the server field

Some of the above examples come fromhttps://www.runoob.com/linux/…