Linux - Shell编程基础
用户和操作系统之间的接口
Shell分类
Shell的双重角色
命令解释程序
Shell的工作步骤
打印提示符
得到命令行
解析命令
查找文件
准备参数
执行命令
独立的程序设计语言解释器
KISS (Keep It Small and Stupid)
可复用工具tools
重定向和管道
也称Shell script(Shell脚本)
是一组命令
#!/bin/sh
ls -al
touch aa
cp aa bb
Shell编程的基础知识
Linux环境
Linux命令
Shell程序结构
Shell脚本的执行方法
#!/bin/sh
# first.sh
# This file looks through all the files in the current
# directory for the string POSIX, and then displays those
# files to the standard output
for file in *
do
if grep –q POSIX $file
then
more $file
fi
done
exit 0
方法1
$ sh script_file
方法2
chmod +x script_file (可选chown, chgrp)
./script_file
方法3
source script_file,或
.script_file
Shell启动文件
sh
/etc/profile login shell, system wide
~/.profile login shell
ENV
csh
/etc/csh.cshrc always, system wide
/etc/csh.login login shell, system wide
~/.cshrc always
~/.login login shell
~/.logout logout shell
/etc/csh.logout logout shell, system wide
tcsh
~/.tcshrc login shell
bash
/etc/profile ? ~/.bash_profile ? ~/.bash_login ? ~/.bash_profile
/etc/bash.bashrc ? ~/.bashrc
BASH_ENV
Shell输入/输出重定向举例
>:输出重定向
$ ls –l > lsoutput.txt
>>:追加
$ ps >> lsoutput.txt
出错输出重定向 (2>)
$ kill –HUP 1234 > killout.txt 2> error.txt
<:输入重定向
$ more < killout.txt
Shell程序设计的语法
Shell环境变量
Shell变量赋值
$ salutation=Hello
$ echo $salutation
Hello
$ salutation="Yes Dear"
$ echo $salutation
Yes Dear
$ salutation=7+5
$ echo $salutation
7+5
Shell变量访问
% echo “$PAGER”
% echo “${PAGER}”
使用{}避免歧异
% temp_name=“haha”
% temp=“hehe”
% echo $temp
hehe
% echo $temp_name
haha
% echo ${temp}_name
hehe_name
% echo ${temp_name}
haha
参数变量和内部变量举例1
假设脚本名为myscript
如果执行./myscript foo bar baz,结果如何?
#!/bin/sh
salutation="Hello"
echo $salutation
echo "The program $0 is now runnning"
echo "The 1st & the 2nd parameters were $1 & $2"
echo $*
exit 0
$ ./myscript foo bar baz
Hello
The program ./myscript is now runnning
The 1st & the 2nd parameters were foo & bar
foo bar baz
参数变量和内部变量举例2
假设脚本名为var3.sh
执行sh ./var3.sh hello world earth,输入如何?
#!/bin/sh
echo "I was called with $# parameters"
echo "My name is $0"
echo "My first parameter is $1"
echo "My second parameter is $2"
echo "All parameters are $@"
$ sh ./var3.sh hello world earth
I was called with 3 parameters
My name is ./var3.sh
My first parameter is hello
My second parameter is world
All parameters are hello world earth
参数变量和内部变量举例3
1 #!/bin/sh
2 echo "What is your name?"
3 read USER_NAME
4 echo "Hello $USER_NAME"
5 echo "File ${USER_NAME}_file will be created"
6 touch "${USER_NAME}_file"
代码说明
第5行使用
Shell变量引用
当包含一个或多个空格时使用”…”
当
在
Shell变量引用举例
#!/bin/sh
myvar="Hi there"
echo $myvar
echo "$myvar"
echo ‘$myvar‘
echo \$myvar
echo Enter some text
read myvar
echo ‘$myvar‘ is $myvar
exit 0
Output
#!/bin/sh
myvar="Hi there"
echo $myvar Hi there
echo "$myvar" Hi there
echo ‘$myvar‘ $myvar
echo \$myvar $myvar
echo Enter some text Enter some text
read myvar Hello?
echo ‘$myvar‘ is $myvar $myvar is Hello
exit 0
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。