logo头像
Snippet 博客主题

Shell命令运算

exit 命令
#!/bin/bash
#退出状态码,最大为255,超过则进行模运算
#testing the exit status
var1=10
var2=20
var3=$[ $var1 + $var2]
echo The answer is $var3
exit 5
使用expr执行数学运算
#!/bin/bash
#An example of using the expr command

var1=10
var2=20
var3=`expr $var2 / $var1`
echo "The result is $var3"
使用内联重定向计算表达式
#!/bin/bash

var1=10.45
var2=43.67
var3=33.2
var4=71

var5=`bc <<EOF
scale=4
a1 = $var1 * $var2
b1 = $var3 * $var4
a1 + b1
EOF
`
echo The final answer for this mess is $var5
使用方括号执行数学运算
#!/bin/bash

var1=10
var2=50
var3=45
var4=$[$var1 * ($var2 - $var3)]
echo 'The final result is '$var4
使用自定义变量
#!/bin/bash
#testing variables

days=10
guest="Katie"
echo "$guest logged in $days days age"
guest="Katie2"
days=5
echo "$guest logged in $days days age"
反引号的使用
#!/bin/bash
#using the backtick character  会把反引号里面当作一条命令来执行

testing=`date`
echo "The date and time are:$testing"
在脚本中使用bc
#!/bin/bash
var1=100
var2=45
var3=`echo "scale=4; $var1 / $var2" | bc`
echo The answer for this is $var3
显示时间和登录者
#!/bin/bash
#This script displays the date and who's logged on

#如果想在同一行显示
#echo -n -e 'The time is:\n\n'
echo The time is:
date
echo The one who has been logged is:
who
显示系统变量和转义字符
#!/bin/bash
#display user information from system

echo "User info fro userId:$USER"
echo UID:$UID
echo HOME:$HOME
#换行
echo -e '\n'      
echo 'The cost of the item is \$15'
通过反引号获得当前日期并生成唯一文件名
#!/bin/bash
#copy the /usr/bin directory listing to a log file

today=`date +%y%m%d`
ls /usr/bin -al > log.$today
支付宝打赏 微信打赏

赞赏是不耍流氓的鼓励