学习shell咯3 博客分类: Linux Bash编程CC++C#
程序员文章站
2024-02-22 16:29:04
...
C shell和TC shell效仿了C语言的预防,儿Bourne shell基于一门古老的编程语言Algol
Bash和Korn shell则综合了Bourne和C shell
Bash Shell语法和结构:
The shbang line
Comment
Wildcards
Display output
Local variables
Global variables
Extracting values from variables
Reading user input
Arguments
Arrays
Command substitution
Arithmetic
Operators
Conditional statements
Loops
Functions
Invitation example of Bash:
Bash和Korn shell则综合了Bourne和C shell
Bash Shell语法和结构:
The shbang line
#!/bin/bash
Comment
# This is a comment
Wildcards
rm *; ls ??; cat file[1-3]; echo "How are you?"
Display output
echo "How are you?"
Local variables
variable_name=value declare variable_name=value name="John Doe" x=5
Global variables
export VARIABLE_NAME=value declare -x VARIABLE_NAME=value export PATH=/bin:/usr/bin:.
Extracting values from variables
echo $variable_name echo $name echo $PATH
Reading user input
echo "What is your name?" read name read name1 name2 ...
Arguments
$ scriptname arg1 arg2 arg3 ... echo $1 $2 $3 echo $* echo $#
Arrays
set apples pears peaches (positional parameters) echo $1 $2 $3 declare -a array_name=(word1 word2 word3) declare -a fruit=( apples pears plums) echo $(fruit[0])
Command substitution
variable_name=`command` variable_name=$( command ) echo $variable_name echo "Today is `date`" echo "Today is $(date)"
Arithmetic
declare -i variable_name typeset -i variable_name (( n=5 + 5)) echo $n
Operators
== != && || ! > >= < <=
Conditional statements
if command then block of statements else if command then block of statements else block of statements fi case variable_name in pattern1) statements ;; pattern2) statements ;; esac
Loops
while command do block of statements done for variable in word_list do block of statements done
Functions
function_name() { block of code } function function_name { block of code }
Invitation example of Bash:
#!/bin/bash # GNU bash versions 2.x # The Party Program––Invitations to friends from the "guest" file guestfile=~/shell/guests if [[ ! –e "$guestfile" ]] then printf "${guestfile##*/} non–existent" exit 1 fi export PLACE="Sarotini's" (( Time=$(date +%H) + 1 )) declare -a foods=(cheese crackers shrimp drinks `"hot dogs"` sandwiches) declare -i n=0 for person in $(cat $guestfile) do if [[ $person == root ]] then continue else # Start of here document mail –v –s "Party" $person <<- FINIS Hi $person! Please join me at $PLACE for a party! Meet me at $Time o'clock. I'll bring the ice cream. Would you please bring ${foods[$n] and anything else you would like to eat? Let me know if you can make it. Hope to see you soon. Your pal, ellie@$(hostname) FINIS n=n+1 if (( ${#foods[*]} == $n )) then declare -a foods=(cheese crackers shrimp drinks `"hot dogs"` sandwiches) n=0 fi fi done printf "Bye..."