shell脚本学习

1、exec命令

An exec <filename command redirects stdin to a file
An exec >filename command redirects stdout to a designated file
exec 2>filename 将会把执行的命令重定向到文件中 

 2、shift命令

        位置参数可以用shift命令左移。比如shift 3表示原来的$4现在变成$1,原来的$5现在变成$2等等,原来的$1、$2、$3丢弃,$0不移动。不带参数的shift命令相当于shift 1。

#!/bin/bash
until [ $# -eq 0 ]
do
  echo "First arguments: $1, Count of arguments: $#"
  shift
done

         输出:

$ ./param.sh 2 3 9 7
First arguments: 2, Count of arguments: 4
First arguments: 3, Count of arguments: 3
First arguments: 9, Count of arguments: 2
First arguments: 7, Count of arguments: 1

3、变量/参数的个数 $#

4、declare 声明变量,-a声明数组,-i声明整型

#!/bin/bash
declare -i a
a=3
echo "a = $a"

declare -a arr
arr='cainiao'
arr[1]='dragonfly'
echo "arr = ${arr[0]}"

     输出

$ ./declare.sh 
a = 3
arr = cainiao

 5、-z 判断字符串为空

#!/bin/bash
if [ -z "$1" ]; then
  echo "First arg is empty"
else
  echo "First argument is $1"
fi

     输出

$ ./zz.sh 
First arg is empty
$ ./zz.sh fun
First argument is fun

 6、-f、-d、-s、-r、-w、-x 判断文件/目录存在、非空、可读、可写、可执行

if [ -f  file ]    如果文件存在
if [ -d ...   ]    如果目录存在
if [ -s file  ]    如果文件存在且非空 
if [ -r file  ]    如果文件存在且可读
if [ -w file  ]    如果文件存在且可写
if [ -x file  ]    如果文件存在且可执行   

 7、dpkg安装失败时候处理,提示如下:

E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?

     把一下命令的输出文件都删除了:

fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock
ls -l /var/lib/dpkg/lock /var/lib/apt/lists/lock 

 8、字符串替换

curl -s $VERSION_URL | tr '\n' ',' | sed 's/,//g

   此处假设VERSION_URL返回值带有一个空行,此处会把空行删掉;tr不能直接把\n替换成'',所以看要转一转

猜你喜欢

转载自yueyemaitian.iteye.com/blog/2324486