shell命令学习笔记

Shell入门笔记

2017-06-29  本文已影响18人  carolwhite

本笔记参考 Linux探索之旅

一.什么是Shell

Shell是指终端命令行环境,是管理命令行的程序。它提供了所有可以让你运行命令的基础功能,比如以下部分功能。

二.Shell种类

Screen Shot 2017-06-29 at 2.52.54 PM.png

ubuntu和mac默认使用bash,我们可以通过chsh命令改变Shell种类

chsh

三.Shell脚本文件

脚本(Script)是批处理文件的延伸,是一种纯文本保存的程序,一般来说的计算机脚本程序是确定的一系列控制计算机进行运算操作动作的组合,在其中可以实现一定的逻辑分支等。

vim test.sh

Shell 脚本文件的后缀是 .sh。这已经成为一种约定俗成的命名惯例了 (sh 就是 shell 的缩写)

在写一个 Shell 脚本时,第一要做的事就是指定要使用哪种 Shell 来 “解析/运行” 它。

#!/bin/bash

只需要写入你想要执行的命令

#!/bin/bash
ls
#!/bin/bash
# 列出目录的文件
ls

1.给脚本文件添加可执行的权限

chmod +x test.sh

2.运行

./test.sh
bash -x test.sh

四.Shell变量

message='Hello World' #=不能空格
echo $message # 变量前加$显示变量的值
message='Hello World'
echo 'The message is $message'
The message is $message
message='Hello World'
echo "The message is $message"
The message is Hello World
message=`pwd`
echo "You are in the directory $message"
You are in the directory /home/exe

#!/bin/bash

read name
echo "Hello $name !"
$ ./a.sh
bai
Hello bai!

参数-p :显示提示信息

#!/bin/bash

read -p 'Please enter your name : ' name
echo "Hello $name !"
$ ./a.sh  
please enter you name :bai
Hello bai!

参数-n :限制字符数目


./variable.sh 参数1 参数2 参数3

这些个 参数1参数2参数3 被称为「参数变量」。
但问题是我们还不知道如何接收这些参数到我们的脚本中。其实不难,因为这些变量是被自动创建的。

$# :包含参数的数目。
$0 :包含被运行的脚本的名称 (我们的示例中就是 variable.sh )。
$1:包含第一个参数。
$2:包含第二个参数。
...
$8 :包含第八个参数。
#!/bin/bash

echo "You have executed $0, there are $# parameters"
echo "The first parameter is $1"
$ ./b.sh 1 2 3 4
You have executed ./b.sh, there are 4 parameters
The first parameter is 1

五.Shell条件

if [ 条件测试 ]
then 
    做这个
fi
if [ 条件测试 ]
then
    做这个
else
    做那个
fi
if [ 条件测试 1 ]
then
    做 1 的事情
elif [ 条件测试 2 ]
then
    做 2 的事情
elif [ 条件测试 3 ]
then
    做 3 的事情
else
    做其他事情
fi
Screen Shot 2017-07-11 at 11.44.59 PM.png

;;相当于break, *)表示其他条件,esac是case倒数表示结束。我们也可以在case 语句的匹配项中做「或」的匹配,但是不是用两个竖线(逻辑或)了,而是用一个竖线。

cat $1 in  
    "1"|"2"|"3")
     echo "1 or 2 or3"
     ;;
    *)
    echo "other"
    ;;
esac
     
Screen Shot 2017-07-11 at 11.39.42 PM.png Screen Shot 2017-07-11 at 11.42.21 PM.png Screen Shot 2017-07-11 at 11.40.25 PM.png

六.Shell循环

while [ 条件测试 ]
do
    做某些事
done
until [ 不满足条件测试 ]
do
    做某些事
done
for 变量 in '值1' '值2' '值3' ... '值n'
do
    做某些事
done
上一篇 下一篇

猜你喜欢

热点阅读