Linux C++学习笔记三——Shell编程


1,Shell脚本第一行必须是:#!/bin/bash。如果使用tc shell,则第一行是:#!/bin/tcsh。

编辑结束并保存后,如果要执行该脚本,最好先使其可执行:chmod +x filename。此后,在该脚本目录下输入如下即可执行脚本:./filename。

2,变量赋值与引用:

格式:变量名=值  -- 要取用一个变量的值,只需在变量名前加一个$

变量的命名,需遵循一定的规则:首个字母必须用字母或下划线;中间不能有空格;不能使用其他标点符号。

Example:

#!/bin/bash
num=2
echo "This is the ${num}nd."
Result:

this is the 2nd.

Note:
Shell的默认赋值是字符串赋值。
3,Shell里的基本语句:

if语句:

if ....; then
  ....
elif ....; then
  ....
else
  ....
fi
也可以使用测试命令,对条件进行测试:

[ -f "somefile" ] --判断是否是一个文件
[ -x "/bin/ls" ]  --判断/bin/ls是否存在并有可执行权限
[ -n "$var" ]     --判断$var变量是否有值
[ "$a" = "$b" ]   --判断$a和$b是否相等 
case语句:

case ... in
   ...) do something here 
   ;;
esac
和C或C++中不同的是,这里的case是用来匹配字符串,而不是数字。

select语句:

select var in ... ; do
 break;
done
.... now $var can be used ....
从一种不同的值中进行选择。

while循环:

while ...; do
   ....
done
for循环:

for var in ....; do
   ....
done


版权声明:本文为cz168love原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。