Getting started with shell programming

Source: Internet
Author: User

Getting started with shell programming

Background

  Shell is an interface for users to interact with the kernel. It is one of the most important software in Linux. Currently, the most popular Shell is bash Shell, which is known for its simplicity and efficiency. It has become a tool for Linux programmers and system administrators to solve practical problems over the years. Shell is the outermost layer of the operating system. Shell merges programming languages to control processes and files, and starts and controls other programs. Shell prompts you to enter the input, explains the input to the operating system, and processes any result output from the operating system to manage the interaction between you and the operating system. Shell provides communication with the operating system. This communication is interactive (input from the keyboard is operated immediately) or executed as a Shell script. Shell scripts are the sequence of Shell and operating system commands, which are stored in files. When you log on to the system, the system locates the name of the Shell to be executed. After it is executed, Shell displays a command prompt. A normal user's prompt is usually a $ (dollar sign ). When you Enter a command at the prompt and press Enter, Shell evaluates the command and tries to execute it. Depending on the command description, Shell writes the command output to the screen or redirects to the output. Then it returns to the command prompt and waits for you to enter another command. The command line is the line where the input is located. It contains the Shell prompt. The basic format of each line is as follows:

  $ Command parameters (one or more)

Shell regards the first word (until the first space) of the command line as the command, and all subsequent words as the independent variable.

Here we recommend that you use zsh, the specific download installation version, please refer to the http://macshuo.com /? P = 676

 

1: Determine whether the file is a block device or character device file. If it is copied to the/dev directory

 

1. The read command reads information from the keyboard or file and assigns it to a variable (one or more) until a carriage return or file Terminator is encountered.
2. I/O devices are generally divided into two categories: Block devices and character devices. Block devices store information in blocks of a fixed size. Each block has its own address. The size of a data block is usually between 512 bytes and 32768 bytes. The basic feature of Block devices is that each block can be read and written independently of other blocks. A disk is the most common block device.

 

#!/bin/bash
read -p "please input a filename:" filenameif test -b "$filename" -o -c "$filename";then echo "$filename is a device file" && cp $filename /develse echo "$filename is not a device file"fi

 

2: Simulate Linux Login Shell

#! /Bin/bash
X = wj # This is the user name y = 1111 # This is the password read-p "please input yourname:" yournameread-p "please input yourkey: "yourkeyif test" $ x "=" $ yourname "-a" $ y "=" $ yourkey "; then bash # note that the space after test cannot be saved
Else
Echo "please try again"
Fi

 

3: read two numbers from the keyboard, compare the two numbers, and print the result.

#!/bin/bash
read -p "please input num1:" num1read -p "please input num2:" num2if test $num1 = $num2 ;then   echo "num1=num2"elif test $num1 -gt $num2 ;then   echo "num1>num2"else test $num1 -lt $num2
  echo "num1<num2"fi

 

4: Check whether the specified file exists in the/root/directory.

#!/bin/bash

cd /rootread -p "please input filename:" filenameif test -e $filename;then echo "$filename is exist"else echo "$filename is not exist"fi

 

5: delete the files with a size of 0 in the current directory

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

 

6: Find the largest file

#!/bin/bash
a=0for name in *do if test -d $name;then
    c=1 else     b=$(ls -l $name | awk '{print $5}')     if test $b -ge $a;then
      a=$b namemax=$name fi fidoneecho "the max file is $namemax"

 

7: print the current user (do not use whoami)

#!/bin/bash

echo "Current User is :"echo $(who | sed -n '1p' | awk '{print $1}')

 

8: search for all files greater than 50 kb in the current directory, write these file names to a text file, and count the number of files.

 

The wc command is used to count the number of bytes, number of words, and number of rows in a specified file, and display the statistical result.

 

#!/bin/bashfind ./ -size +50k > toingji.txt cat tongji.txt |wc -l   

 

9: a function that uses shift to calculate the product of all parameters. Assume that all parameters are integers.

1. the expr command is a Linux Command, which is generally used for integer calculation, but can also be used for string operations.

2. For a command line parameter, the number of parameters can be unfixed, but you can use $ * or $ @ to perform cyclic operations. If you want Shell to process parameters one by one without knowing the number of variables, that is, after $1 is $2 and after $2 is $3. $1 is available before the shift command is run. After the shift command is run, the original $2 will become $1 and the original $1 will become unavailable, the number of parameters obtained using the $ # command is also less than 1.

3. shift: used for left-shift command line parameters

#! /Bin/bashresult = 1
#$ # The number of parameters while test $ #-gt 0do result = 'expr $1 \ * $ result 'shiftdoneecho "the result is $ result"

 

 

10: test whether a file has been sorted

#! /Bin/bashread-p "please input your filename:" filesort-C $ file
# $? Indicates the return value of the previous command execution (display the exit status of the last command. 0 indicates no error. Other values indicate an error)
A = $?
If test $ a-eq 0; then
Echo "$ file is youxu"
Else
Echo "$ file is wuxu"
Fi

 

11: Determine whether the user is running

#!/bin/bash

a=$(ps | grep "$$" | awk '{print $2}')b=$( who| grep "$a" | awk '{print $1}')read -p "please input a username:" usernameif [ "$b" = "$username" ];then echo "the ueser is running"else echo "the ueser is not running"fi

 

12: Create a folder interactively in the current directory. (If the folder already exists, enter a new name)

#!/bin/bashread -p "please input dirname:" fileif test -d $file;then    echo dir is exist please try againelse    read -p "create dir now?[y/n] " sel    if test "$sel" = "y";then        mkdir $file    elif test "$sel" = "n";then        bash    else        echo "Your input is wrong"    fifi

 

13: get the IP address of the Local Machine

#! /Bin/basha = $ (ifconfig | grep "inet address:" | awk '{print $2}' | sed's/address: // G' | sed-n '1p') echo "ip is $"

 

14: Print password-free users

#! /Bin/bashecho "no passwd user are:" a = $ (sudo cat/etc/shadow | grep "*" | awk 'begin {FS = ": "} {print $1} ') # Before processing the input file, the domain separator (FS) is set to colon echo $

 

15: write a script to calculate the factorial of n in a loop.

#!/bin/bashread -p "please input n:" nsum=1for a in `seq 1 $n`do       sum=`expr $sum \* $a`doneecho "n! = $sum"

 

16: Use the case statement to test whether the input character is: lowercase/uppercase/number/others

#!/bin/bashread -p "please input something:" Keycase $Key in        [[:lower:]]) echo "It is lowercase";;        [[:upper:]]) echo "It is uppercase";;        [0-9]) echo "It is number";;esac

 

17: test whether the file contains specific text content

#! /Bin/bashread-p "enter a string:" stringread-p "enter a filename: "filenamegrep-q" $ string "$ filename # search for str in file (NO content found is output). If yes, return 0if test $? -Eq 0; then echo "The text exists in the file" else echo "Text does not exist in the file" fi

 

18: Check whether a given word is a word in the dictionary.

#! /Bin/bashread-p "enter a string:" string
#/Usr/share/dict/american-english is a dictionary file for the list of commonly used english words in the ubuntu system.
grep -q "$string" /usr/share/dict/american-englishif test $? -eq 0;then    echo "match directionary"else    echo "not match directionary"fi

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.