linux shell

1: The default of linux is to use bash xx.sh or ./xx.sh when executing shell scripts

 

 

As mentioned above, Shell is a scripting language, so there must be an interpreter to execute these scripts.

Common shell script interpreters on Unix/Linux include bash, sh, csh, ksh, etc., which are customarily called a kind of shell. We often talk about how many kinds of shells there are, but we are actually talking about shell script interpreters.

bash

Bash is the standard default shell of Linux, and this tutorial is also based on bash. Bash is jointly completed by Brian Fox and Chet Ramey. It is the abbreviation of BourneAgain Shell, and there are a total of 40 internal commands.

Linux uses it as the default shell because it has features such as:

  • You can use the functions similar to doskey under DOS, and use the arrow keys to view and quickly enter and modify commands.
  • Automatically give commands starting with a string by looking for a match.
  • Contains its own help function, you only need to type help below the prompt to get related help.

 

sh

Developed by Steve Bourne, sh is short for Bourne Shell, sh is the default shell of the Unix standard.

ash

The ash shell is written by Kenneth Almquist, a small shell that occupies the least system resources in Linux. It only contains 24 internal commands, so it is very inconvenient to use.

csh

csh is a relatively large kernel of Linux. It is compiled by a total of 47 authors represented by William Joy, and has a total of 52 internal commands. The shell actually points to a shell such as /bin/tcsh, that is to say, csh is actually tcsh.

ksh

ksh is an acronym for Korn shell, written by Eric Gisin, and has a total of 42 internal commands. The biggest advantage of this shell is that it is almost completely compatible with the commercial distribution of ksh, so that you can try the performance of the commercial version without paying for the commercial version.

Note: bash is the abbreviation of Bourne Again Shell, which is the default shell of linux standard. It is based on Bourne shell and absorbs some features of C shell and Korn shell. Bash is fully compatible with sh, that is, scripts written in sh can be executed in bash without modification.

-----------------

  1. #!/bin/bash
  2. echo "Hello World !"

There are two ways to run a shell script.

as an executable program

Save the above code as test.sh and cd to the corresponding directory:
chmod +x ./test.sh #Make the script have execute permission
./test.sh #Execute the script
Note that it must be written as ./test.sh, not test.sh. The same is true for running other binary programs, write test.sh directly, the Linux system will go to the PATH to find out if there is a test.sh, and only /bin, /sbin, /usr/bin, /usr/sbin, etc. are in the PATH , your current directory is usually not in the PATH, so if you write test.sh, the command will not be found. Use ./test.sh to tell the system to look for it in the current directory.

To run a bash script in this way, the first line must be written correctly so that the system can find the correct interpreter.

The "system" here is actually the application of the shell (imagine Windows Explorer), but I deliberately write it as the system to facilitate understanding. Since the system refers to the shell, is a script that uses /bin/sh as the interpreter? Can the first line be omitted? Yes

 

----------------------

define variable

  1. variableName="value"

Note that there can be no spaces between the variable name and the equals sign, which may be different from all programming languages ​​you are familiar with. At the same time, the naming of variable names must follow the following rules:

  • The first character must be a letter (az, AZ).
  • There can be no spaces in between, you can use an underscore (_).
  • Punctuation marks cannot be used.
  • You cannot use keywords in bash (reserved keywords can be viewed with the help command).

----------------------

use variables

To use a defined variable, just add a dollar sign ($) in front of the variable name, for example:
  1. your_name="mozhiyan"
  2. echo $your_name
  3. echo ${your_name}

 

----------------------

redefine variable

Defined variables can be redefined, such as:
  1. myUrl="http://see.xidian.edu.cn/cpp/linux/"
  2. echo ${myUrl}
  3. myUrl="http://see.xidian.edu.cn/cpp/shell/"
  4. echo ${myUrl}
It is legal to write this way, but note that $myUrl="http://see.xidian.edu.cn/cpp/shell/" cannot be written when assigning the second time, and the dollar sign ($) is added when using variables .

read-only variable

Use the readonly command to define a variable as a read-only variable, and the value of a read-only variable cannot be changed.

The following example attempts to change a read-only variable, and results in an error:
  1. #!/bin/bash
  2. myUrl="http://see.xidian.edu.cn/cpp/shell/"
  3. readonly myUrl
  4. myUrl="http://see.xidian.edu.cn/cpp/danpianji/"
Running the script yields the following results:
/bin/sh: NAME: This variable is read only.

delete variable

Variables can be deleted using the unset command. grammar:
  1. unset variable_name
After a variable is deleted, it cannot be used again; the unset command cannot delete a read-only variable.

for example:
  1. #!/bin/sh
  2. myUrl="http://see.xidian.edu.cn/cpp/u/xitong/"
  3. unset myUrl
  4. echo $myUrl
The above script does not have any output.

variable type

When running the shell, three variables exist at the same time:

1) Local variables

Local variables are defined in scripts or commands and are only valid in the current shell instance. Programs started by other shells cannot access local variables.

2) Environment variables

All programs, including those started by the shell, have access to environment variables, and some programs require environment variables to function properly. Shell scripts can also define environment variables when necessary.

3) shell variables

Shell variables are special variables set by the shell program. Some of the shell variables are environment variables and some are local variables. These variables ensure the normal operation of the shell ---------------------- #!/bin/ bash
echo "test"
myaa="aa"
echo $myaa
echo "ccc"
#practice echo
"start practice"
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[ 3]="Ayan"
NAME[4]="Daisy"
echo "${NAME[*]}"
echo "S${NAME[@]}"
echo 'special variable'
echo $$
echo $0
echo "expression"
a=10
b=11

if [ $a == $b ]
then
echo "a==b"
else
echo "a!=b"






factorial=`expr $factorial \* $a`
done 
echo "10! = $factorial"

echo '例子2 输入end才结束'
unset var 
while [ "$var" != "end" ]
 do     
      echo -n "please input a number: "
      read var
      if [ "$var" = "end" ]
      then          
       break    
      fi      
      echo "var is $var"
done

echo '例子3 查找/root/目录下是否存在该文件'

#/bin/bash
echo "enter a file name:"
read a
if test  -e /root/$a
then echo "the file is exist!"
else echo "the file is not exist!"
fi    

----------------------

 

I wrote a small shell example by myself. Although it is very small, all large programs are piled up by small modules. Programmers must know how to write a script, and I only work under linux. So I can only write linux shell scripts, huh, this article will be updated one after another, cheer for myself!

1. Simulate linux login shell

#/bin/bash
echo -n "login:"
read name
echo -n "password:"
read passwd
if [ $name = "cht" -a $passwd = "abc" ];then
echo " the host and password is right!"
else echo "input is error!"
fi

2. Compare two numbers

#/bin/bash
echo "please enter two number"
read a
read b
if test $a -eq $b
then echo "NO.1 = NO.2"
elif test $a -gt $b
then echo "NO.1 > NO.2"
else echo "NO.1 < NO.2"
fi

3.



read a
if test  -e /root/$a
then echo "the file is exist!"
else echo "the file is not exist!"
fi

4.for循环的使用

#/bin/bash
clear
for num in 1 2 3 4 5 6 7 8 9 10
do
    echo "$num"
done

5.命令行输入

#/bin/bash
echo "Please enter a user:"
read a
b=$(whoami)
if test $a = $b
then echo "the user is running."
else echo "the user is not running."
fi

6.删除当前目录下大小为0的文件

#/bin/bash
for filename in `ls`
do
    if test -d $filename
    then b=0
    else   
       a=$(ls -l $filename | awk '{ print $5 }')
            if test $a -eq 0
             then rm $filename
             fi
        fi     
done

7. If there is a file under /export/um_lpp_source, then change its file system size to 3G

 #/bin/bash
while line=`ls /export/um_lpp_source`
do
        if test $line=""
        then echo "NULL"
             sleep 1
    else echo $line
                chfs -a size=3G /export/um_lpp_source
                 exit 0
        fi
done

 

8. Test IP address

#/bin/bash
for i in 1 2 3 4 5 6 7 8 9
do
    echo "the number of $i computer is "
    ping -c 1 192.168.0.$i
done

9. If the size of test.log is greater than 0, then copy the *.tar.gz file in the /opt directory

 #/bin/sh
a=2
while name="test.log"
do
        sleep 1
        b=$(ls -l $name | awk '{print $5}')
        if test $b -ge $a
        #then echo "OK "
    then `cp /opt/*.tar.gz .`
        exit 0
        fi
done

10. Print what was read, in preparation for the following example

#/bin/bash
while read name
do
echo $name
done

11. From 0. Read the content in sh and print it

#/bin/bash
while read line
do
    echo $line
done < 0.sh

12. Read the content in ac and add 1

#/bin/bash
test -e ac
while read line
do
    a=$(($line+1))
done < ac
echo $a

13. Ordinary parameterless function

#/bin/bash
p ()
{
    echo "hello"
}
p

14. Pass parameters to the function

#/bin/bash
p_num ()
{
    num=$1
    echo $num
}
for n in $@
do
    p_num $n
done

15. Create folder

#/bin/bash
while :
do
    echo "please input file's name:"
    read a
    if test -e /root/$a
    then
         echo "the file is existing Please input new file name:"
    else
        mkdir $a
        echo "you aye sussesful!"
        break
    fi
done

16. Get the local IP address

#/bin/bash
ifconfig | grep "inet addr:" | awk '{ print $2 }'| sed 's/addr://g'

17. Find the largest file

#/bin/bash
a=0
for name in *.*
do
     b=$ (ls -l $name | awk '{print $5}')
    if test $b -ge $a
    then a=$b
         namemax=$name
     fi
done
echo "the max file is $namemax"

18. Find the current network segment IP user, redirect to ip.txt file

#/bin/bash
a=1
while :
do
    a=$(($a+1))
    if test $a -gt 255
    then break
    else
        echo $(ping -c 1 192.168.0.$a | grep "ttl" | awk '{print $4}'| sed 's/://g')
        ip=$(ping -c 1 192.168.0.$a | grep "ttl" | awk '{print $4}'| sed 's/://g')
        echo $ip >> ip.txt
    fi
done

19. Print the current user

#/bin/bash
echo "Current User is :"
echo $(ps | grep "$$" | awk '{print $2}')

20.case statement Exercise

#!/bin/bash
clear
echo "enter a number from 1 to 5:"
read num
case $num in
    1) echo "you enter 1"
    ;;
    2) echo "you enter 2"
    ;;
    3) echo "you enter 3"
    ;;
    4) echo "you enter 4"
    ;;
    5) echo "you enter 5"
    ;;
    *) echo "error"
    ;;
esac

21.yes/no returns a different structure

#!/bin/bash
clear
echo "enter [y/n]:"
read a
case $a in
    y|Y|Yes|YES) echo "you enter $a"
    ;;
    n|N|NO|no) echo "you enter $a"
    ;;
    *) echo "error"
    ;;
esac

22.杀进程

 #/bin/bash
pid=`ps -ef | grep '进程相关内容' | grep -v 'grep' | awk '{ print $2}'`
if [ -n "$pid" ]; then
        kill -9 $pid
fi

 23.内置命令的使用

#/bin/bash

    clear
        echo "Hello, $USER"
        echo
       
        echo "Today 's date id `date`"

        echo

        echo "the user is :"
        who
        echo

        echo "this is `uname -s`"
        echo

        echo "that's all folks! "

24.

 

 

25.

#/bin/bash
26. Print No Password User

#/bin/bash
echo "No Password User are :"
echo $(cat /etc/shadow | grep "!!" | awk 'BEGIN { FS=" :" }{print $1}')

27.

#/bin/bash

    clear
        echo "Hello, $USER"
        echo
       
        echo "Today 's date id `date`"

        echo

        echo "the user is :"
        who
        echo

        echo "this is `uname -s`"
        echo

        echo "that's all folks! "


28. Check if the port number is enabled
#!/bin/bash
n=1
echo "Check xxx service..."
while true
do
        if test $n -gt 20
        then
                echo "xxx service failed to start"
                break
        fi
               
        sleep 5
        n=$(($n+1))
        port=`netstat -antp | grep "0.0.0.0:8080"`
        if [ ${#port} -gt 3 ]; then
                echo "xxx service has been started"
                break;
        fi
done

----------------------

----------------------

----------------------

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326688922&siteId=291194637