Shell 脚本攻略-小试牛刀

2018-03-18  本文已影响0人  羊陆之交

在终端中打印

Script

#!/bin/bash
echo hello world
echo 'hello world'
echo "hello world"

echo -e "1\t2\t3"
echo "1\t2\t3"

Note

变量和环境变量

Script

#!/bin/bash
var=123456

echo $var
echo ${var}

echo "var length is: ${#var}"

var_quote="123456"
[ $var -eq $var_quote ] && echo 'var equals to var_quote'
[ $var == $var_quote ] && echo 'var equals to var_quote'
[ $var = $var_quote ] && echo 'var equals to var_quote'

Output

123456
123456
var length is: 6
var equals to var_quote
var equals to var_quote
var equals to var_quote

Note

数学运算

Script

#!/bin/bash
i=1
j=2
let k=i+j
echo k=i+j is: $k

let k++
echo k++ is: $k

let k--
echo k-- is: $k

k=$((i + j))
echo "(()) operator: $k"

k=$[i + j]
echo [] operator: $k

Note

重定向文件描述符

Script

#!/bin/bash
file_name=/tmp/temp.txt
touch $file_name

echo "hello" > $file_name
ls + &> $file_name
echo "append" >> $file_name

ls + 2>> $file_name
ls . 1>> $file_name

Note

数组和关联数组

Script

#!/bin/bash
array1=(1 2 3)
echo array1 is: ${array1[*]}

array2[0]=1
array2[1]=2
array2[2]=3
echo array2 is: ${array2[*]}
echo array2 length is: ${#array2[*]}

Note

函数和参数

Script

#!/bin/bash
fn()
{
    echo '$0 is: '$0
    echo '$1 is: '$1
    echo '$2 is: '$2
    echo '$@ is: '$@
    echo '$* is: '$*
    return 10
}

fn 1 2
echo return value is: $?

Note

将命令的输出存到变量中

Script

#!/bin/bash
file_name=/tmp/tmp.txt
echo -e "1\n2\n3" > $file_name

cmd_output=$(cat $file_name)
echo $cmd_output

cmd_output=`cat $file_name`
echo $cmd_output
上一篇 下一篇

猜你喜欢

热点阅读