Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

4.2.1 Write a simple script


May 23, 2021 That's what Linux should learn



It is estimated that after reading the complex description of Shell's script above, the reader will feel tired of not loving it. However, the above refers to an advanced Shell scripting principle, which actually uses the Vim editor to write Linux commands sequentially to a file, which is a simple script.

For example, if you want to see the current working path and list all the file and property information in the current directory, the script that implements this should look something like this:

[root@linuxprobe ~]# vim example.sh

!/bin/bash

  1. #For Example BY linuxprobe.com
  2. pwd
  3. ls -al

The name of the Shell script file can be arbitrary, but to avoid being mistaken for a normal file, it is recommended that you add the .sh suffix to indicate that it is a script file. I n this example.sh script above, three different elements actually appear: the first line of the script declaration ( s!) is used to tell the system which Shell interpreter to use to execute the script; W hat the?! You don't believe it's as simple as writing a script, so let's take a look at the results:

[root@linuxprobe ~]# bash example.sh /root/Desktop total 8 drwxr-xr-x. 2 root root 23 Jul 23 17:31 . d r-xr-x---. 1 4 root root 4096 Jul 23 17:31 .. - rwxr--r--. 1 root root 55 Jul 23 17:31 example.sh

In addition to running the Shell script file directly with the bash interpreter command above, the second way to run the script is by entering the full path. B y default, however, error information is prompted for insufficient permissions, and you only need to add execution permissions to the script file (see Chapter 5). Readers who are studying Linux for the first time are not anxious, and it's not too late to do this experiment after the next chapter has learned the user's identity and permissions:

[root@linuxprobe ~]# ./example.sh bash: ./Example.sh: Permission denied [root@linuxprobe ~]# chmod u+x example.sh [root@linuxprobe ~]# ./example.sh /root/Desktop total 8 drwxr-xr-x. 2 root root 23 Jul 23 17:31 . d r-xr-x---. 1 4 root root 4096 Jul 23 17:31 .. - rwxr--r--. 1 root root 55 Jul 23 17:31 example.sh