Common commands and statements for Shell programming (scripting)

Source: Internet
Author: User
Tags echo command first string

some common shell programming (script) commands and statements can be used to meet general requirements.
command parameters Received:
    • Number of parameters:
$#
    • Parameter values:
The command itself: $ A first parameter: $ $ ...
Exit Command:Exit
echo Command:
    • Line break:
Echo
    • No line break after output:
Echo- N"Please select (y/n)?" "
    • Output double quotes with escape symbols:
echo "Welcome \" "Official Server \" Deployment Tool. "
    • Output with variable:
echo "Upcoming Deployment project:$project _name"
    • Output a string with an escape character:
Echo- e"First\ tSecond
    • Output to File
Append to end of file: Echo-e $log _info>>Deploy.log Overwrite file contents: Echo-e $log _info>Deploy.log
printf Command: (can replace echo, formatted output, same as printf function in C language)

    • Output a number of two digits after the decimal point, and wrap:
printf "The number is%.2f.\ n"100
    • Outputs a string of a specified width:
Left-justified: printf "%-20s%-15s%10.2f\n "Stephen" "Liu" 35 right-aligned: printf "|%10s|\n "Hello
variables:
    • Defined:
profile= "Production"
    • Use:
Echo $ profile
    • Variable stitching:
log_info= "$log _info, $target _ip"
array:
    • Defined:
servers= ("192.168.0.31" "192.168.0.39")projects= ("Public" "Industry" "Logistics" "misc")
    • Get the entire array:
${projects[*]}
    • Get the number of array elements:
${#servers [@]}
The IF statement (conditional judgment also applies to the while statement and the For statement):
    • Determine if a variable (project) is not empty:
if [ $project];thenecho "Variable \" Project\ "is null." Fi
    • Judgment is not equal to:
if [$#-ne3];then echo "command line parameter not 3" fi
    • Boolean-Valued Judgment:
if [ "$is _ip_correct" = False ];thenecho "Invalid IP address, please use one of the following IPs:" Echo ${servers[*]} exit fi
    • String Equality judgment:
If["$confirm" = = "Y"]&&["$confirm"! = "n"];d o # do something...fi
    • Regular expression judgment
if [[$ =~ ^public|industry$]] && [[$ =~ ^[yn]$]];then # do something...fi
If[ [! $deploy _more =~ [yn] ]; then # do something...fi
    • Determine if the file exists:
if [!- Ftarget/$project. War];then # do something ...
Fi
    • Determine if the directory exists:
if [- D$2/webapps/$1];then # do something...fi
    • To determine the suffix of a file name (string)
Backup_file= "/backup/java_data/$1-$today. War" backup_file= "/backup/java_data/$1-$today. Gz"
if ["${backup_file##*.}"= "war"];then CP $backup _file $1.war elif ["${backup_file##*.}"= "GZ"];then tar zxvf $backup _file else echo "backup file format not" Exit fi
Read statement (reads the string entered by the user):
    • The simplest usage: Read user input to variable yes_or_no
Read Yes_or_no
    • Prompt user to enter Y or n
read-e-P "Do you want to back up: (y/n)? "-I" Y "needbackup(Parameter Description:-e: I do not know what is the use, but if removed, I will fail;-P: followed by the prompt statement;-I: followed by the default input; the last parameter is the variable that holds the user input.))
Select statement (prompting the user to select one from the list):
    • Modify the default prompt (the default value is "#?") ):
ps3="Please select an item:"
    • Prompts the user to select a value from the array:
Selectproject in ${projects[*]};d o if [$project];then break FI-Done
or add exit Condition: Select Target_ip in${servers[*]}"Exit (Exit)";d o if [" $target _ip "=" exit (exit) "]; Then echo "Thank you for using!" good-bye! "Break fi
If [$target _ip]; Then # does something fi done
Case Statement:Case $project inPublic )project_name= "Volkswagen Edition";;Logistics)project_name= "Deliveryversion" ;;misc)project_name= "Miscellaneous edition";;Esac
While statement:
    • Match regular expressions to determine the use:
while [[! $needbackup =~ ^[yn]$]];d o read-e-P "Backup: (y/n)? "-I" Y "needbackup done
    • Make a progress bar with "..."
Echo-n "Wait for the $port port to open ..." while [! $pid _new];d o #sleep 1 pid_new= ' NETSTAT-NLP | grep $port | awk ' {print $7} ' | Awk-f "/" ' {print '} ' echo-n ' ... "done
For statement:
    • Traverse:
For ip_t in ${servers[*]};d o If ["$" = "$ip _t"];then is_ip_correct=true break Fidone
Call other programs:
    • Use ', and get the output result:
ps3= "Please choose a branch:" Select Branch in' svn list svn://<svn_host>/java/code/branches ';d o if [$branch];then svn_dir= "svn://<svn_host>/java/code/branches/$branch" project_dir=$ Branch break FI-Done
    • using $ (), and obtain the output result:
today=$ (Date+%y-%m-%d/%h:%m:%s)svn_version=$(SVN info $SVN _dir | grep "Last Changed Rev:" | awk ' {print $4} ')
    • Invoke other programs silently (without outputting results, output to a null device)
RM $2/logs/m* $2/logs/l* $2/logs/h* $2/logs/catalina.2015*&>/dev/null &
awk (used to slice a string, typically with grep):
    • Get the fourth string separated by a space:
svn_version=$ (svn info $svn _dir | grep "Last Changed Rev:" |awk ' {print $4} ')

    • Gets the first string separated by a special delimiter ("/")
Awk- F "/"' {print '} '
    • Get all the port numbers for the $port process and kill
For PID in ' NETSTAT-NLP | grep $port | awk ' {print $7} ' | Awk-f "/" ' {print $} ' do echo ' ==========================warning======================== ' echo ' does not close the process properly, port: $port, Kill directly, Process number: $pid "echo" ==========================warning======================== "Kill $piddone
(original article, reprint please specify the blog from Clement-xu)

Copyright NOTICE: This article is the original article, reprint please indicate the CSDN blog which is transferred from Clement-xu.

Common commands and statements for Shell programming (scripting)

Related Article

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.