Common Commands and Statements for Shell Programming (Scripting)

Some commonly used Shell programming (script) commands and statements can meet general needs.
Received command parameters: Number of parameters
: $#
Parameter value: Command itself: $0 First parameter: $1 Second parameter: $2 ......
Exit command: exit
echo command:
newline: echo
does not wrap after output: echo - n "Please choose (y/n)?"
Use escape symbols to output double quotes: echo "Welcome to \"Official Server\"Deployment Tools."
Output with variables: echo "Project to be deployed: $project_name"
output with turn Descriptor string: echo -e "first\tsecond"
output to the file Append to the end of the file: echo -e $log_info >> deploy.log Overwrite the file content: echo -e $log_info > deploy.log
printf command: (You can Instead of echo, format the output, which has the same function as the printf function in the C language) to

output a number with two decimal places and a newline: printf "The number is %.2f.\n" 100
Output a string with a specified width: Left: printf "%-20s %-15s %10.2f\n" "Stephen" "Liu" 35 Right: printf "|%10s|\n"



Variable concatenation: log_info="$log_info,$target_ip"
Array:
Definition: servers=("192.168.0.31" "192.168.0.39") projects=("public" "industry" "logistics" "misc")
to get the entire array: ${projects
  • }
  • Get the number of array elements: ${#servers[@]}
    if statement (conditional judgment also applies to while statement and for statement): to
    determine whether a variable (project) is not empty: if [ $project ];then echo "Variable \ "project\" is null." fi
    judgment is not equal to: if [ $# -ne 3 ];then echo "command line parameters are not 3" fi
    boolean judgment: if [ "$is_ip_correct" = false ];then echo " Invalid ip address, please use one of the following ip:" echo ${servers
  • } exit fi
  • String equality judgment: if [ "$confirm" == "y" ] && [ "$confirm" != "n" ];do # do something... fi
    regular expression judgment if [[ $1 =~ ^public |industry$ ]] && [[ $3 =~ ^[yn]$ ]];then # do something... fi
    if [[ ! $deploy_more =~ [yn] ]];then # do something... fi
    judgment Whether the file exists: if [ ! -f target/$project.war ];then # do something...
    fi
    to judge whether the directory exists: if [ -d $2/webapps/$1 ];then # do something... fi to
    judge A filename (string) with a suffix 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 "The format of the backup file is incorrect" exit fi
    read statement (read user input string):
    the simplest usage: read user input to variable yes_or_no read yes_or_no
    Prompt the user to enter y or n read -e -p "Backup: (y/n)?" -i "y" needbackup (parameter description: -e: I don't know what it is, but if it is removed, -i will be invalid ;-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 (prompt the user to choose one from the list):
    modify the default prompt (the default value is " #?"): PS3="Please select a project:"
    Prompts the user to select a value from the array: select project in ${projects
  • };do if [ $project ];then break fi done
  • Or add an exit condition: select target_ip in ${servers
  • } "Exit";do if [ "$target_ip" = "Exit" ]; then echo "Thanks for using! Good-Bye!" break fi
  • if [ $target_ip ]; then # do something fi done
    case statement: case $project in public) project_name="public version" ;; logistics) project_name="delivery version" ;; misc) project_name="miscellaneous version" ;; esac
    while statement:
    Use with regular expression judgment: while [[ ! $needbackup =~ ^[yn]$ ]];do read -e -p "Whether backup: (y/n)?" -i "y" needbackup done
    Use "..." for progress bar echo -n "Wait for $port to open..." while [ ! $pid_new ];do #sleep 1 pid_new=`netstat -nlp | grep $port | awk '{print $7}' | awk -F "/" '{print $1}'` echo -n "…" done
    for statement:
    Traversal: for ip_t in ${servers
  • };do if [ "$2" = "$ip_t" ];then is_ip_correct=true break fi done
  • Call other programs:
    use ``, and get the output: PS3="Please select a branch:" select branch in `svn list svn:///java/code/branches`;do if [ $branch ];then svn_dir= "svn:///java/code/branches/$branch" project_dir=$branch break fi done
    use $() and get the output: today=$(date +%Y-%m-%d/%H: %M:%S) svn_version=$(svn info $svn_dir | grep "Last Changed Rev:" | awk '{print $4}')
    silently call other programs (do not output results, that is, output the results to a null device ) rm $2/logs/m* $2/logs/l* $2/logs/h* $2/logs/catalina.2015* &>/dev/null &
    awk (used to slice strings, generally used with grep ):
    to get the fourth string separated by spaces: svn_version=$(svn info $svn_dir | grep "Last Changed Rev:" | awk '{print $4}')

    to get the special delimiter ("/") separated The first string awk -F "/" '{print $1}'
    Get all processes with port number $port and kill for pid in `netstat -nlp | grep $port | awk '{print $7}' | awk -F "/" '{print $1}'` do echo "= ==========================Warning========================== " echo "Cannot close the process normally, port: $port, kill directly, process ID: $pid" echo "========================== =Warning==========================" kill $pid done

    Guess you like

    Origin http://43.154.161.224:23101/article/api/json?id=326320440&siteId=291194637