第一个脚本文件
代码如下:
#!/bin/bash
echo "This is my first bash code!"
exit 0
重定向符号和数学计算
代码如下:
#!/bin/bash
echo -n "The time and date are: "
date
value1=100 #等号前后不允许出现空格
value2=$value1
echo -n "value1="
echo $value1
echo -n "value2="
echo $value2
ls -l | sort > out.txt #管道符号(|)和重定向输出符号>
ls -l >> out.txt #重定向追加输出符号>>
echo -n "wc<out.txt:"
wc < out.txt #重定向输入符号<
echo "sort<<EOF ... EOF"
sort << EOF #内置输入重定向<<
`date`
EOF
#数学计算
echo -n "expr进行计算:1+5="
expr 1+5
echo -n "使用方括号进行计算:1+5="
echo $[1+5]
echo "使用bc计算器进行浮点运算"
var1=100
var2=200
var3=`echo "scale=4;$var1/$var2" | bc`
echo "$var1 / $var2 = $var3"
var4=71
var5=`bc<<EOF
scale=4
a1=($var1*$var2)
b1=($var3*$var4)
a1+b1
EOF`
echo "var5=$var5"
exit 0
使用test命令
代码如下:
#!/bin/bash
#使用test命令
var1=10
var2=100
if [ $var1 -gt $var2 ]
then
echo "var1 grate var2"
else
echo "var2 grate var1"
fi
#只能比较整数
test_user=hanxi
if [ $USER = $test_user ]
then
echo "Welcome $test_user"
fi
str1=Hanxi
str2=hanxi
if [ $str1 /> $str2 ]
then
echo "$str1 > $str2"
else
echo "$str1 < $str2"
fi
if [ -n $str1 ]
then
echo "The string '$str1' is not empty"
else
echo "the string '$str1' is empty"
fi
#检查文件目录
if [ -d $HOME ]
then
echo "your Home dir exists"
cd $HOME
ls -a
else
echo "there's a problem with your HOME dir"
fi
pwfile=/etc/shadow
if [ -f $pwfile ]
then
if [ -r $pwfile ]
then
tail $pwfile
else
echo "Sorry, I'm unable to reas the $pwfile file "
fi
else
echo "Sorry, the file $pwfile doesn't exist"
fi
if [[ $USER == h* ]]
then
echo "Hello $USER"
else
echo "Sorry, I don't know you"
fi
循环语句
代码如下:
#!/bin/bash
for file in /home/hanxi/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done
var1=10
while [ $var1 -gt 0 ]
do
echo $var1
新闻热点
疑难解答