shell学习记录

来源:互联网 发布:澳洲新闻软件下载 编辑:程序博客网 时间:2024/05/02 02:34
</pre><pre code_snippet_id="1831820" snippet_file_name="blog_20160815_1_930458" name="code" class="plain">#!/bin/sh


变量名和等号之间不能有空格:

your_name="runoob.com"

使用一个定义过的变量,只要在变量名前面加美元符号即可:

your_name="qinjx"echo $your_nameecho ${your_name}


重新定义变量:

my_name="sunteng"echo $my_namemy_name=123echo $my_name


只读变量:

my_name="sunteng"readonly my_namemy_name="stevesun"


删除变量:

my_name="sunteng"echo $my_nameunset my_nameecho $my_name


shell中单引号内的字符串原样输出,双引号内的字符串能转义、能包含变量:

my_name="sunteng"echo "your name is \"$my_name\""

拼接字符串:

your_name="qinjx"greeting="hello,"$your_name" !"greeting_1="hello, ${your_name} !"echo $greeting $greeting_1

获取字符串长度:

string="abcd"echo ${#string}


提取子字符串:

string="runoob is a great site"echo ${string:1:4}

反引号内的命令直接执行:

CUR=`pwd`echo $CUR


数组相关:

array_text=("12" "abd" "dfad" "ewfw")echo ${array_text[1]}echo ${array_text[@]}echo ${#array_text[@]}echo ${#array_text[*]}echo ${#array_text[1]}


printf:

printf "%-10s %-8s %-4s\n" 姓名 性别 体重kgprintf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234printf "%-10s %-8s %-4.2f\n" 杨过 男 48.6543printf "%-10s %-8s %-4.2f\n" 郭芙 女 47.9876

printf "%d %s\n" 1 "abc"printf '%d %s\n' 1 "abc"printf %s abcdefprintf "\n"printf %s abc defprintf "\n"printf "%s\n" abc defprintf "%s %s %s \n" a b c d e f g h i jprintf "%s and %d \n"


test命令:

num1=100num2=100if test $num1 -eq $num2then    echo '两个数相等!'else    echo '两个数不相等!'fi


流程控制:

a=10b=20if [ $a == $b ]then    echo "a 等于 b"elif [ $a -gt $b ]then    echo "a 大于 b"elif [ $a -lt $b ]then    echo "a 小于 b"else    echo "没有符合的条件"fi



0 0
原创粉丝点击