文章目录
前言
Shell 编程能提升我们工作效率,但 bash 和 csh 有一定的区别。下面将整理两者不同,以及常用的语法经验。具体代码可以去我的GitHub下载。
1. 变量和环境变量设置
1. csh
set x = 1
echo $x
setenv MATH true
2. bash
x=1
echo $x
MATH=true
export MATH=true
echo $MATH
2. if语句
1. csh
if (2 != 3 ) then
echo "2 != 3"
endif
2. bash
if [[ 2 != 3 ]];then
echo "2 != 3"
fi
3. while循环
1. csh
set sum = 0
set i = 1
while ($i <= 10)
set sum = `expr ${sum} + ${i}`
set i = `expr ${i} + 1`
end
echo 'sum = '$sum
输出:sum = 55
2. bash
i=1
sum=0
while [[ $i -le 10 ]]
do
((sum += i))
let i++
done
echo 'sum = '$sum
输出:sum = 55
4. 数组
1. csh
echo 'array_start'
set array = (5, 4, 3, 1, 2)
echo $#array
foreach i (${array[*]})
echo $i
end
echo 'array_end'
输出:
2. bash
echo 'array_start'
array=(5 4 3 1 2)
echo ${array[@]}
for i in ${array[@]}; do
echo $i
done
echo 'array_end'
输出:
5. 获取当前文件路径
1. csh
#!/bin/csh
#Method 1
set script_dir=`readlink -f -- "$0"`
set CURDIR=`dirname -- $script_dir`
echo $CURDIR
#Method 2
set root=`pwd`
echo $root
2. bash
#!/bin/bash
#Method 1
CURDIR=$(cd $(dirname ${BASH_SOURCE[0]}); pwd )
echo $CURDIR
#Method 2
root=`pwd`
echo $root
6. 获取当前时间
1. csh
#!/bin/csh
set ddate=`date`
echo $ddate
2. bash
#!/bin/bash
date=$(date)
echo $date
7. 产生随机数并测试
1. csh
#!/bin/csh
set extraratio = 10
set sum = 0
set ij = 1
while ($ij <= 100)
set rand = `date +%N`
set rand100 = `expr ${rand} % 100`
if ( `expr ${rand100}` < ${extraratio} ) then
set sum = `expr ${sum} + 1`
endif
set ij = `expr $ij + 1`
end
echo ${sum}
2. bash
#!/bin/bash
extraratio=10
sum=0
ij=0
#echo $ij
while [[ $ij -le 100 ]]
do
rand=`date +%N`
#echo $rand
rand100=`expr ${rand} % 100`
#echo $rand100
if [[ ${rand100} -le ${extraratio} ]]; then
((sum += 1))
fi
let ij++
done
echo 'sum = '$sum
8. 补充
1. 查看系统默认用的 Shell
echo $SHELL
2. 查看系统所拥有的 Shell
cat /etc/shells