Cシェル(csh) Bシェル(sh)コマンド

Bシェル

#!/bin/sh
echo "Hello World"

Cシェル

#!/bin/csh -f
echo "Hello World"

シェル変数セット
sh:

hoge=FUGA

csh:

set hoge=FUGA

環境変数セット
sh:

HOGE=FUGA
export HOGE
export HOGE=FUGA (一部 sh・bash の方言)

csh:

setenv HOGE FUGA

変数参照・変数代入
sh:

echo $i
j=$i

csh:

echo $i
set j=$i

一定回数のループ
sh:
>|sh|
i=0
while [ $i -lt 5 ]; do
    echo $i
    i=`expr $i + 1`
done

csh:

set i=0
while ( $i < 5 )
    echo $i
    @ i = $i + 1
end

行単位の処理
sh:
コマンド実行結果を利用:

ls -l | while read line; do
    echo $line
done

ファイル:

while read line; do
    echo $line
done < file.txt

ドキュメント:

while read line; do
    echo $line
done <<END
hoge
fuga
END

csh:

while true
do
    echo $line
done

リスト処理
sh:

vars="x y z"
for var in $vars; do
    echo $var
done

csh:

set vars=(x y z)
foreach var ($vars)
    echo $var
end

コマンド実行結果のリスト処理
sh:

for file in `ls`; do
    echo $file
done

csh:

foreach file (`ls`)
    echo $file
end

if 文
sh:

if [ $var = "scott" ]; then
    echo "var is scott"
elif [ $var = "tiger" ]; then
    echo "var is tiger"
else
    echo "var is not scott nor tiger"
fi

csh:

if ( $var = "scott" ) then
    echo "var is scott"
else if ( $var = "tiger" ) then
    echo "var is tiger"
else
    echo "var is not scott nor tiger"
endif

continue・break
sh:

for file in `ls`; do
    if [ $file = "hoge.txt" ]; then continue
    if [ $file = "fuga.txt" ]; then break
done

csh:

foreach file (`ls`)
    if ( $file = "hoge.txt" ) then
        continue
    endif
    if ( $file = "fuga.txt" ) then
        break
    endif
end

switch 文
sh:

case $var in
hoge)
    echo "var is hoge"
    ;;
foo|bar)
    echo "var is foo or bar"
    ;;
*)
    echo "var is unknown"
    ;;
esac

csh:

switch ($var)
case "hoge":
    echo "var is hoge"
    breaksw
case "foo":
case "bar":
    echo "var is foo or bar"
    breaksw
default:
    echo "var is unknown"
    breaksw
endsw

シェルプログラミング実用テクニック (Software Design plus)

シェルプログラミング実用テクニック (Software Design plus)

入門UNIXシェルプログラミング―シェルの基礎から学ぶUNIXの世界

入門UNIXシェルプログラミング―シェルの基礎から学ぶUNIXの世界