#!/bin/sh
myvar="Hi there"
echo $myvar // Hi there
echo "$myvar" // Hi there
echo "myvar" // myvar
echo '$myvar' // $myvar
echo 'myvar' // myvar
echo /$myvar // $myvar
echo /myvar // myvar
echo Enter some text // Enter some text
read myvar // 等待输入
// 输入 HOW DO YOU DO
echo '$myvar' now equals $myvar // $myvar now equals HOW DO YOU DO
exit 0
$ IFS=''
$ set foo bar bam
$ echo $@
foo bar bam
$ echo "$@"
foo bar bam
$ echo $*
foo bar bam
$ echo "$*"
foobarbam
$ unset IFS
$ echo $IFS
$ echo "$*"
foo bar bam
如果想访问脚本程序的参数,用 $@ 最好
sa="Hello" //
echo $sa //Hello
echo "The program $0 is now running" // biangliang shell脚本的名字
echo "The second parameter was $2" // bar
echo "The first parameter was $1" // foo
echo "The parameter list was $*" //foo bar baz
echo "The script is now complete"
$ /bin/sh bianliang foo bar baz
2.6.2 条件
shell脚本对任何从命令行上被调用的命令的退出码进行测试。
test / [ 布尔判断命令 且" ["用“]”来结尾
if [ -f /bin/bash ] //注意保持距离
then
echo "file /bin/bash exists"
fi
if [ -d /bin/bash ]
then
echo "/bin/bash is a directory"
else
echo "/bin/bash is NOT a directory"
fi
执行结果为:
$ /bin/sh panduan
file /bin/bash exists
/bin/bash is NOT a directory
2.6.3 控制结构
echo "Please answer yes or no : Is it morning?" //shell用echo -e,bash用echo -n来去除换行符
read timeofday
if [ $timeofday = "yes" ] //一定要保持距离 if[ $timeofday 不行 ; if [ $timeofday="yes"也不行
then
echo "Good morning"
elif [ $timeofday = "no" ] //[ 对timeofday的内容进行测试,测试结果由if判断
then
echo "Good afternoon"
else
echo "Sorry,$timeofday is not recognized.Enter yes or no!"
exit 1
fi
exit 0
看似完美的程序,其实隐患重重,在不输入任何数据,直接ENTER后
[: 15: yes: unexpected operator
[: 15: no: unexpected operator
Sorry, is not recognized.Enter yes or no!
问题出在 当直接ENTER后,$timeofday 成为 空字符串
因此将 $timeofday 改为"$timeofday"
4 for 语句
for 循环经常与shell的文件名扩展一起使用
for variable in values_table
do
...$variable
done
for 循环经常与shell的文件名扩展一起使用
for file in *.sh
还有就是
for foo in 10
echo "here wo go"
这样能执行一次
for foo in 1 2 3 4 5 6 7 8 9 10
echo "here wo go"
却可以执行10次
而
for foo in 1 2 3 5 8 9 41 10 1 0
echo "here wo go"
依然是执行10次