美文网首页
Shell 基础

Shell 基础

作者: NJHu | 来源:发表于2019-01-21 19:53 被阅读11次

简单

" "

huxupeng:~ huxupeng$ echo "
> yan
> c
> 1
> "

yan
c
1

读取

read

echo "hello world"
echo "what is your name?"
read PERSON
echo "hello, $PERSON"

变量

variable=value
variable='value'
variable="value"

大括号

skill="java"
echo "i am learn ${skill}Script"

单引号和双引号

url="https"
web1='c ${url}'
web2="c ${url}"

echo $web1
echo $web2

c ${url}
c https

command

$()

shText=$(cat first.sh)
echo $shText 

只读变量

readonly

myName="jack"
readonly myName
myName="rose"

删除变量

unset variable_name

myUrl="http://see.xidian.edu.cn/cpp/u/xitong/"
unset myUrl
echo $myUrl

特殊变量

image.png

命令行参数

sh first.sh a b

#!/bin/bash
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"

File Name: first.sh
First Parameter : a
First Parameter : b
Quoted Values: a b
Quoted Values: a b
Total Number of Parameters : 2

* 和@ 的区别

* 和@ 都表示传递给函数或脚本的所有参数,不被双引号(" ")包含时,都以"1" "2" … "$n" 的形式输出所有参数。

但是当它们被双引号(" ")包含时,"*" 会将所有的参数作为一个整体,以"1 2 …n"的形式输出所有参数;"@" 会将各个参数分开,以"1" "2" … "n" 的形式输出所有参数。

#!/bin/bash
echo "\$*=" $*
echo "\"\$*\"=" "$*"
echo "\$@=" $@
echo "\"\$@\"=" "$@"
echo "print each param from \$*"
for var in $*
do
    echo "$var"
done
echo "print each param from \$@"
for var in $@
do
    echo "$var"
done
echo "print each param from \"\$*\""
for var in "$*"
do
    echo "$var"
done
echo "print each param from \"\$@\""
for var in "$@"
do
    echo "$var"
done



$*=  a b c d
"$*"= a b c d
$@=  a b c d
"$@"= a b c d
print each param from $*
a
b
c
d
print each param from $@
a
b
c
d
print each param from "$*"
a b c d
print each param from "$@"
a
b
c
d

转换

-E 选项禁止转义

...

命令替换是指Shell可以先执行命令,将输出结果暂时保存,在适当的地方输出。command

#!/bin/bash
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; uptime`
echo "Uptime is $UP"
image.png
#!/bin/bash

echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"

echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"

unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"

var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"

echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"

加减乘除

#!/bin/sh
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
if [ $a == $b ]
then
   echo "a is equal to b"
fi
if [ $a != $b ]
then
   echo "a is not equal to b"
fi

关系运算符

image.png

bool 运算

image.png

字符串运算

image.png

检测文件属性

image.png

拼接字符串

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

获取字符串长度

string="abcd"
echo ${#string} #输出 4

提取子字符串

string="alibaba is a great company"
echo ${string:1:4} #输出liba

数组

array_name=(
    value0
    value1
    value2
    value3
    value4
)

array_name[5]=value5

array_name[7]=value6

echo ${array_name[5]} ${array_name[7]} ${array_name[6]}

获取数组的长度

# 取得数组元素的个数
length=${#array_name[@]}
# 或者
length=${#array_name[*]}
# 取得数组单个元素的长度
lengthn=${#array_name[n]}

显示换行

echo "OK!\n"
echo "It is a test"

显示不换行

echo "OK!\c"
echo "It is a test"

原样输出字符串

echo '$name\"'

显示命令执行结果

echo `date`

显示结果重定向至文件

echo "It is a test" > myfile

printf

# format-string为双引号
$ printf "%d %s\n" 1 "abc"
1 abc
# 单引号与双引号效果一样 
$ printf '%d %s\n' 1 "abc" 
1 abc
# 没有引号也可以输出
$ printf %s abcdef
abcdef
# 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用
$ printf %s abc def
abcdef
$ printf "%s\n" abc def
abc
def
$ printf "%s %s %s\n" a b c d e f g h i j
a b c
d e f
g h i
j
# 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替
$ printf "%s and %d \n" 
and 0
# 如果以 %d 的格式来显示字符串,那么会有警告,提示无效的数字,此时默认置为 0
$ printf "The first program always prints'%s,%d\n'" Hello Shell
-bash: printf: Shell: invalid number
The first program always prints 'Hello,0'

if

#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi

test

test 命令用于检查某个条件是否成立,与方括号([ ])类似。

test
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi
num1=100
num2=100
if test num1=num2
then
    echo 'The two strings are equal!'
else
    echo 'The two strings are not equal!'
fi
文件测试
cd /bin
if test -e ./bash
then
    echo 'The file already exists!'
else
    echo 'The file does not exists!'
fi

另外,Shell还提供了与( ! )、或( -o )、非( -a )三个逻辑操作符用于将测试条件连接起来,其优先级为:“!”最高,“-a”次之,“-o”最低。例如:


cd /bin
if test -e ./notFile -o ./bash
then
    echo 'One file exists at least!'
else
    echo 'Both dose not exists!'
fi

case-esac

echo 'Input a number between 1 to 4'
echo 'Your number is:\c'
read aNum
case $aNum in
    1)  echo 'You select 1'
    ;;
    2)  echo 'You select 2'
    ;;
    3)  echo 'You select 3'
    ;;
    4)  echo 'You select 4'
    ;;
    *)  echo 'You do not select a number between 1 to 4'
    ;;
esac

for循环

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done
for str in 'This is a string'
do
    echo $str
done
#!/bin/bash
for FILE in $HOME/.bash*
do
   echo $FILE
done

while循环

COUNTER=0
while [ ${COUNTER} -lt 5 ]
do
    COUNTER=`expr $COUNTER + 1`
    echo $COUNTER
done
COUNTER=0
while [ ${COUNTER} -lt 5 ]
do
    COUNTER=$(expr $COUNTER + 1)
    echo $COUNTER
done
echo 'type <CTRL-D> to terminate'
echo -n 'enter your most liked film: '
while read FILM
do
    echo "Yeah! great film the $FILM"
done

break

#!/bin/bash
while :
do
    echo -n "Input a number between 1 to 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "Your number is $aNum!"
        ;;
        *) echo "You do not select a number between 1 to 5, game is over!"
            break
        ;;
    esac
done

break n

#!/bin/bash
for var1 in 1 2 3
do
   for var2 in 0 5
   do
      if [ $var1 -eq 2 -a $var2 -eq 0 ]
      then
         break 2
      else
         echo "$var1 $var2"
      fi
   done
done
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
   Q=`expr $NUM % 2`
   if [ $Q -eq 0 ]
   then
      echo "Number is an even number!!"
      continue
   fi
   echo "Found odd number"
done

Shell函数

#!/bin/bash
# Define your function here
Hello () {
   echo "Url is http://see.xidian.edu.cn/cpp/shell/"
}
# Invoke your function
Hello

带有return语句的函数:

#!/bin/bash
funWithReturn(){
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
# Capture value returnd by last command
ret=$?
echo "The sum of two numbers is $ret !"

Shell函数参数

#!/bin/bash
funWithParam(){
    echo "The value of the first parameter is $1 !"
    echo "The value of the second parameter is $2 !"
    echo "The value of the tenth parameter is $10 !"
    echo "The value of the tenth parameter is ${10} !"
    echo "The value of the eleventh parameter is ${11} !"
    echo "The amount of the parameters is $# !"  # 参数个数
    echo "The string of the parameters is $* !"  # 传递给函数的所有参数
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

Shell文件包含

#!/bin/bash
. ./subscript.sh
echo $url

相关文章

网友评论

      本文标题:Shell 基础

      本文链接:https://www.haomeiwen.com/subject/wcoceftx.html