Linux Shell脚本快速入门

前言

开始使用Ubuntu操作系统,感觉还是很好用的,但是对于Shell脚本也是零基础,于是打算学习下。以下是一个简单的小结。(学习Linux 命令对于Android的开发也大有帮助)

脚本语言,既然冠之以“语言”,就说明它跟其他C/C++等编译语言在形式上是完全一样的,有变量,有函数,有if,else,while等条件分支,只是脚本语言是解释性的执行:碰到一句,解释一句,执行。

写一个脚本看一看

运行脚本之前,需要做三件事情:

  • 写一个脚本
  • 使Shell有权限执行该脚本
  • 把脚本放在Shell可以找到的地方

打开文本编辑器,输入下列文本,保存为my_scripts.sh:

#!/bin/bash
# this is my first shell script

echo "hello shell scripts"

第一脚本就写成了。运行脚本之前,你可能需要修改脚本的权限:

chmod 755 my_scripts

输入下面命令执行脚本:

./my_scripts.sh

基础

变量

shell脚本提供了不少环境变量来获取系统信息,如用户名,主机名,时间等:

$HOSTNAME,$USER,$DATE

这些变量是全局的,在任何时候都可以使用。但,要在脚本中使用的变量(变量无需声明,直接使用即可),却并不具备这样的全局性,例如,有如下脚本 myvar.sh:

#! /bin/sh
echo "MY_VAR is: $MY_VAR"
MY_VAR= "hi, there"
echo "MY_VAR is : $MY_VAR"

执行如下脚本命令:

$ MY_VAR=hello
$ ./myvar.sh
MY_VAR is:
MY_VAR is: hi, there

输出:

MY_VAR is:
MY_VAR is: hi, there

因而,变量MY_VAR并不具有全局的作用域,如果要像环境变量一样使用该变量,必须将其export:

$ MY_VAR=hello
$ export MY_VAR
$ ./myvar.sh
MY_VAR is:
MY_VAR is: hi, there

这样输出就变了:

MY_VAR is: hello
MY_VAR is: hi, there

附几个比较特殊的变量:

  • $$ 该脚本对应的PID(进程ID)
  • $? 上一个脚本命令的退出条件值

函数

function fcn_name(){ ... }

那么,怎么知道函数的参数了?很简单,$1对应第一个参数,$2对应第二个参数,以此类推,$0则表示执行脚本本身的名字,另外有几个个比较特殊的变量:

  • $# 函数的参数个数(执行脚本的参数)
  • $@ 除了脚本名外所有的参数,$1 $2 ....

    #! /bin/sh
    while [  "$#" -gt "0"  ]
    do
        echo "\$1 is $1"
        shift
    done
    

不是还有递归吗?Shell脚本同样可以实现:

#! /bin/sh
factor()
{
    if [ "$1" -gt  "1" ]; then
        i= 'expr $1 - 1'
        j='factor $i'
        k='expr $1 \* $j'
        echo $k
    else
        echo 1
    fi
}

while:
do
    echo "enter a number"
    read  x
    factor $x
done

语句

多举几个栗子就看懂了。

if/else 条件判断
# first form
if condition ; then
    commands
fi

# Second form
if condition ; then
    commands
else
    commands
fi

# Third form
if condition ; then
    commands
elif condition ; then
    commands
fi
循环
#! /bin/sh
for i in 1 2 3 5 9
do
    echo "number $i"
done

#! /bin/sh
INPUT_STR=hello
while [ "$INPUT_STR" != "bye" ]
do
    echo "Please type something (bye to quit)"
    read INPUT_STR
    echo "you just typed: $INPUT_STR"
done
Case
#! /bin/sh
echo "please say something to me..."

while  :

do 
    read INPUT_STR
    case $INPUT_STR in
            hello)
                        echo "hello you too!"
                        ;;
            bye)
                      echo "See you again!"
                      break;
                      ;;
        *)
                     echo "fail to understand"
                     ;;
     esac
done

echo
echo "that's the all my folks!"

退出条件

应用执行是否成功的标志,是一个0~255之间的整数,0表示应用没有发生错误,执行成功;其他任何值都表示发生了错误。

$? 即可查看一个命令是否执行成功。

例如判断某个文件是否存在:

if [ -f .bash_profile ]; then
    echo "You have a .bash_profile. Things are fine."
else
    echo "Yikes! You have no .bash_profile!"
fi

命令索引

ExpressionDescriptionExample
&run the previous command in the backgroundls &
&&logical ANDif [ "$foo" -ge "0" ] && [ "$foo" -le "9" ]
orlogical ORif [ "$foo" -ge "0" ] or [ "$foo" -le "9" ]
^start of linegrep "^foo
$end of linegrep "foo$
=string equlityif [ "$foo" = "bar" ]
!logical NOTif [ "$foo" != "bar" ]
$$pid of current shellecho "PID=$$
$!pid of last background commandls & echo "PID of ls = $!
&?exit status of last commandls; echo "ls returned code $?
$0name of current commandecho "I am $0"
$1name of 1st parameterecho "first argument is $1
$9name of 9th parameterecho "nith argument is $9
$@all of current commands’ parameters(preserving whitespace/quoting)echo "my arguments are $@
$*all of current commands’ parameters(not preserving whitespace/quoting)echo "my arguments are $*
-d fileTrue if file is a directoryif [ -d /bin ]
-e fileTrue if file existsif [ -e /home/bin/my.text ]
-f fileTrue if file exists and is a regular fileif [ -f /bin/fs]
-L fileTrue if file is symbolic linkif [ -L /bin/fs ]
-r fileTrue if file is readableif [ -r /bin/fs ]
-w fileTrue if file is writableif [ -w /bin/fs ]
-x fileTrue if file is executableif [ -x /bin/fs ]
f1 -nt f2True if f1 is newer than f2(modification time)if [ "@f1" -nt "$f2" ]
f1 -ot f2True if f1 is older than f2if [ "@f1" -ot "$f2" ]
-z stringTrue if string is emptyif [ -z "$f00" ]
-n stringTrue if string is not emptyif [ -n "$f00" ]
str1=str2True if str1 equal str2if [ "$foo" = "bar" ]
str1!=str2True if str1 not equal to str2if [ "$foo" != "bar" ]

Markdown显示原因: or实际为 ||

参考文献

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值