很久之前自己学习过linux的常用shell命令,但是没有记下来,有些生疏,这次自己记录一下,也方便自己以后查看。
本笔记主要学习GNU bash shell的基本命令和操作,在Ubuntu16.04下使用。
简介
Shell也称为“壳”,是用户和内核之间的桥梁。我们都知道Linux系统很多都没有图形界面,很多运维人员都不会给Linux系统安装图形界面,因为图形界面可以实现的功能是很受限制的,而且还很占用资源。于是Linux的使用者大都需要使用命令行,即使是使用Ubuntu这样的桌面系统也是需要大量使用命令行的。很多命令是重复的,常常输命令行其实是很费时间的,有一个好办法就是通过编写shell脚本将命令行保存下来,下次直接直接执行就好了。这样就可以避免每次都一条一条地输命令。
默认的bash shell提示符是美元符号($),在Ubuntu上,使用快捷键"Ctrl+Alt+T"进入的就是shell命令窗口。
第一个shell脚本
新建一个文档,保存为 .sh结尾的文件,例如保存为"hello.sh"。在文件输入一下内容。
这里"echo"是表示输出的意思。
#!/bin/bash
echo "Hello World!"
"#!"又称幻数,#! 是一个约定的标记,它告诉系统这个脚本需要什么解释器来执行,即使用哪一种 Shell。
运行方式:
- 切换到文件所在目录 ,在命令行输入 以下命令:
sh hello.sh - 切换到文件所在目录,输入以下命令(注意是 ./hello.sh,不是hello.sh):
chmod +x ./hellow.sh #使脚本具有执行权限
./hello.sh #执行脚本
输出:Hello World!
一个简单的学习脚本
#!/bin/bash
echo "Hello,this is a simple code for study.You can try it by yourself."
echo "Hello $LOGNAME,it's nice talking to you."
echo "your present working directory is `pwd`."
echo "You are working on a machine called 'HP-246-G3'."
echo "Here is a list of your root files."
echo "------------------------------------------"
cd ~/ #change to root file ------cd 表示切换目录 ~/ 表示的是用户的主目录
ls #list the files in the root file -----其中 ls 表示列出当前工作目录下的文件列表。
echo "------------------------------------------"
echo "Bye,$LOGNAME.The time is `date +%Y-%m-%d` `date +%T`!"
Hello,this is a simple code for study.You can try it by yourself.
Hello zhao,it's nice talking to you.
your present working directory is /home/zhao/linux_shell.
You are working on a machine called 'HP-246-G3'.
Here is a list of your root files.
------------------------------------------
anaconda3 Desktop linux_shell Templates zhao zhao3
cpu.cpp~ Documents Music test.py zhao1.c #zhao3.cpp#
create Downloads Pictures Videos zhao2 zhao3.cpp
create_1 examples.desktop Public workspace zhao2.cpp zhao.c
------------------------------------------
Bye,zhao.The time is 2018-11-07 21:37:34!
通过这个程序可以看出,使用shell脚本和其他编程语言是类似的。