read的使用,与用户交互,shell空格
#!/bin/bash
echo "请输入密码:"
read passwd
if [ "$passwd" = "1111" ]
then
echo "密码正确"
echo "请输入一个'model':"
read model
if [ "$model" = "open" -o "$model" = "normal" ]
then
echo "模式是$model"
else
echo "请输入open或者normal"
fi
path_open=/home/sysadmin/opennormalmarket/open
path_normal=/home/sysadmin/opennormalmarket/normal
path_target=
file=
case $model in
open)
cd $path_open
cp $file $path_target
echo "已修改为open模式"
;;
normal)
cd $path_normal
cp $file $path_target
echo "已修改为normal模式"
;;
esac
else
echo "请输入正确的密码"
fi
....
关于空格的问题:
http://ganjp.iteye.com/blog/1109207
今天第一次看Shell脚本的编程,发现老么多空格的错误: 然后去查找了一下资料 转载了一篇文章
http://blog.sina.com.cn/s/blog_45497dfa0100kczc.html
1:
定义变量时, =号的两边不可以留空格. 这里不能添加的原因是 添加了空格一般是用来表示判断的
eg:
gender=femal------------right
gender =femal-----------wrong
gender= femal-----------wrong
2
条件测试语句 [ 符号的两边都要留空格 . //这条真的比较膈应人
eg:
if [ $gender = femal ]; then-------right.
fi
if[ $gender...-----------------------wrong
if [$gender...----------------------wrong.
3
条件测试的内容,如果是字符串比较的话, 比较符号两边要留空格!
eg:
if [ $gender = femal ]; then-------right.
if [ $gender= femal ]; then--------wrong.
if [ $gender=femal ]; then---------wrong.
4
如果if 和 then写在同一行, 那么,注意, then的前面要跟上 ; 号.
如果 then 换行写, 那么也没问题.
eg:
if [ $gender = femal ]; then-------right.
if [ $gender = femal ]
then-------------------------------right.
if [ $gender = femal ] then-------wrong. then前面少了 ; 号.
提示出错信息:
syntax error near unexpected token then 这就话出错还可能是由于第二条 "[" 左右都要有空格造成的
同理,还有很多出错信息 比如
syntax error near unexpected token fi 等都是这样引起的.
5
if 后面一定要跟上 then. 同理
elif 后面一定要跟上 then.
不然提示出错信息:
syntax error near unexpected token else
1)if 语句后面需要跟着then,同时前面要有分号;
2) 空格非常重要,shell 会认为空格前的为一个命令,如果a=3 认为是赋值操作,如果写成a = 3,那么就会认为a为一个命令 this=`ls -l |grep '^-' | wc -l `
3) 操作符之间要用空格分开 ,如 test ! -d $1,其中的!和-d就要用空格分开
空格是命令解析中的重要分隔符
=======================================
关于逻辑表达式的问题:
http://www.diybl.com/course/3_program/shell/shelljs/20101230/548509.html
逻辑与的表达:
1)、if [ $xxx=a -a $xx=b ]
2)、if [ $xxx=a ] && [ $xx=b ]
逻辑或的表达:
1)、if [ $xxx=a -o $xx=b ]
2)、if [ $xxx=a ] || [ $xx=b ]
http://hi.baidu.com/ryouaki/item/0689dcb8a467b5a7eaba9319
基本上和其他脚本语言一样。没有太大区别。不过值得注意的是。[]里面的条件判断。
1 字符串判断
str1 = str2 当两个串有相同内容、长度时为真
str1 != str2 当串str1和str2不等时为真
-n str1 当串的长度大于0时为真(串非空)
-z str1 当串的长度为0时为真(空串)
str1 当串str1为非空时为真
2 数字的判断
int1 -eq int2 两数相等为真
int1 -ne int2 两数不等为真
int1 -gt int2 int1大于int2为真
int1 -ge int2 int1大于等于int2为真
int1 -lt int2 int1小于int2为真
int1 -le int2 int1小于等于int2为真
3 文件的判断
-r file 用户可读为真
-w file 用户可写为真
-x file 用户可执行为真
-f file 文件为正规文件为真
-d file 文件为目录为真
-c file 文件为字符特殊文件为真
-b file 文件为块特殊文件为真
-s file 文件大小非0时为真
-t file 当文件描述符(默认为1)指定的设备为终端时为真
3 复杂逻辑判断
-a 与
-o 或
! 非
结尾
语法虽然简单,但是在SHELL里使用的时候,他的功能变得强大了。