勉強する


C shellとTC shellはC言語の予防に倣い、児Bourne shellは古いプログラミング言語Algolに基づいている.
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..."