学习shell咯3
C shell和TC shell效仿了C语言的预防,儿Bourne shell基于一门古老的编程语言AlgolBash和Korn shell则综合了Bourne和C shell
Bash Shell语法和结构:
The shbang line
#!/bin/bash
Comment
# This is a comment
Wildcards
rm *; ls ??; cat file;echo "How are you?"
Display output
echo "How are you?"
Local variables
variable_name=valuedeclare variable_name=valuename="John Doe"x=5
Global variables
export VARIABLE_NAME=valuedeclare -x VARIABLE_NAME=valueexport PATH=/bin:/usr/bin:.
Extracting values from variables
echo $variable_nameecho $nameecho $PATH
Reading user input
echo "What is your name?"read nameread name1 name2 ...
Arguments
$ scriptname arg1 arg2 arg3 ...echo $1 $2 $3echo $*echo $#
Arrays
set apples pears peaches (positional parameters)echo $1 $2 $3declare -a array_name=(word1 word2 word3)declare -a fruit=( apples pears plums)echo $(fruit)
Command substitution
variable_name=`command`variable_name=$( command )echo $variable_nameecho "Today is `date`"echo "Today is $(date)"
Arithmetic
declare -i variable_nametypeset -i variable_name(( n=5 + 5))echo $n
Operators
==!=&&||!>>=<<=
Conditional statements
if commandthenblock of statementselse if commandthenblock of statementselseblock of statementsficase variable_name inpattern1) statements ;;pattern2) statements ;;esac
Loops
while commanddoblock of statementsdonefor variable in word_listdoblock of statementsdone
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" fileguestfile=~/shell/guestsif [[ ! –e "$guestfile" ]]thenprintf "${guestfile##*/} non–existent"exit 1fiexport PLACE="Sarotini's"(( Time=$(date +%H) + 1 ))declare -a foods=(cheese crackers shrimp drinks `"hot dogs"` sandwiches)declare -in=0for person in $(cat $guestfile)doif[[ $person == root ]]then continueelse # 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 fifidoneprintf "Bye..."
页:
[1]