#!/bin/bash# Here is commentsforfilein *;doifgrep –l POSIX $file;thenmore$filefidoneexit0
2.3. 执行脚本文件
Method 1: sh script_file
Method 2:
chmod +x script_file (chown, chgrp optionally)
./script_file
Method 3:
source script_file, or
./script_file
2.4. 用户环境
.bash_profile, .bash_logout, .bashrc files
.bash_profile: 用户登录时被读取,其中包含的命令被bash执行
.bashrc: 启动一个新的shell时读取并执行
.bash_logout: 登录退出时读取执行
Alias
alias/unaliascommand
环境变量
export command
export, env & set command
2.5. 变量
用户变量
环境变量
参数变量和内部变量
2.5.1. 用户变量
用户变量:
用户在shell脚本里定义的变量
变量的赋值和使用
var=value
echo $var
read命令
用法:read var 或read
REPLY variable
引号的用法
双引号,单引号
转义符""
2.5.2. read 用法
#! /bin/bashecho -n "Enter your name: "# 参数-n的作用是不换行,echo默认是换行read name #从键盘输入echo"hello $name, welcome to my program"exit0#退出shell程序。
read -p "Enter your name:" name #-p参数,允许在read命令行中直接指定一个提示
read -p "Enter a number:" number
echo $number
exit 0
#! /bin/bash
# 5s内输入
if read -t 5 -p "please enter your name:" name
then
echo "hello $name, welcome to my script"
else
echo "sorry, too slow"
fi
exit 0
#! /bin/bash
# 只读取一个字符
read -n1 -p "DO you want to continue[ Y/N] ?" answer
case $answer in
Y|y)
echo "fine, continue";;
N|n)
echo "ok, good bye";;
*)
echo "error choice";;
esac
exit 0
#! /bin/bash
# 不显示输入
read -s -p "Enter your password: " pass
echo "your password is $pass"
exit 0
#! /bin/bash
count=1
cat viewFile.sh| while read line
do
echo "Scount:$line"
count=$(($count + 1))
done
echo "Total Count:$count"
exit 0
# eg.1 .bash_profileif[ -f ~/.bashrc ];then. ~/.bashrc
fi# eg.2# !/bin/shecho"Is this morning? Please answer yes or no."read answer
if["$answer"="yes"];thenecho"Good morning"elif["$answer"="no"];thenecho"Good afternoon"elseecho"Sorry, $answer not recognized. Enter yes or no"exit1fiexit0
2.14.2. case语句
形式
case str in
str1 | str2) statements;;
str3 | str4) statements;;
*) statements;;esac
例子Eg
#!/bin/shecho"Is this morning? Please answer yes or no."read answer
case"$answer"inyes| y | Yes | YES)echo"Good morning!";;
no | n | No | NO)echo"Good afternoon!";;
*)echo"Sorry, answer not recognized.";;esacexit0
2.15. 重复语句
2.15.1. for语句
形式
forvarin list
do
statements
done
适用于对一系列字符串循环处理
#!/bin/shforfilein$(ls f*.sh);dolpr$filedoneexit0
2.15.2. while语句
形式
while condition
do
statements
done
例子
quit=n
while["$quit"!="y"];doread menu_choice
case"$menu_choice"in
a) do_something;;
b) do_anotherthing;;
…
q|Q)quit=y;;
*)echo"Sorry, choice not recognized.";;esacdonea=0while["$a" -le "$LIMIT"]doa=$(($a+1))if["$a" -gt 2]thenbreak# Skip entire rest of loop.fiecho -n "$a"done