shell脚本的作用
目前我对于shell脚本的理解就是将多条命令行放入一个文件中,,通过执行这个文件来执行其中的命令,而不需要一个一个的去执行那些命令,将工作变简单。
shell脚本的运行
使用./或者bash命令来执行脚本时,都是在一个新的bash环境中执行脚本的命令,子进程执行结束后其中的变量就释放掉了,在父进程中无法看到。但是通过source执行脚本时,是在父进程中执行,就能获取变量的值。
shell脚本的默认变量
$0:执行的脚本文件名
$1:第一个参数
$#:表示脚本文件执行时后边接的参数个数
$@:表示每个参数的内容
条件判断
格式:
if [条件]; then
fi
多重条件判断
函数
示例
读取输入,并输出
#!/bin/bash
read -p "Please input your first name: " firstname
read -p "Please input your last name: " lastname
echo -e "\nYour full name is: ${firstname} ${lastname}."
根据输入创建文件
#!/bin/bash
echo -e "I will use 'touch' command to create 3 files."
read -p "Please intput your filename: " fileuser
filename=${fileuser:-"filename"}
date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}
touch "${file1}"
touch "${file2}"
touch "${file3}"
文件判断
#!/bin/bash
echo -e "Please input a filename, I will check the filename's type and permission. \n\n"
read -p "Input a filename: " filename
test -z ${filename} && echo "YOU MUST input a filename." && exit 0
test ! -e ${filename} && echo "The filename ${filename} DO NOT exit" && exit 0
test -f ${filename} && filetype="regulare file"
test -d ${filename} && filetype="directory"
test -r ${filename} && perm="readable"
test -r ${filename} && perm="${perm} writable"
test -r ${filename} && perm="${perm} executable"
echo "The filename: ${filename} is a ${filetype}"
echo "And the permissions for you are: ${perm}"
默认变量输出
#!/bin/bash
echo "The script name is ==> ${0}"
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
echo "The first parameter is ==> ${1}"
条件判断
#!/bin/bash
read -p "Please input (Y/N): " yn
if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then
echo "Ok,continue"
exit 0
fi
if [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then
echo "Oh,interrupt!"
exit 0
fi
echo "I don't know what your choice is " && exit 0
多重条件判断
#!/bin/bash
if [ "${1}" == "hello" ]; then
echo "Hello, how are you?"
elif [ "${1}" == "" ]; then
echo "You MUST input parameters, ex> {${0} someword}"
else
echo "The only parameter is 'hello', ex> {${0} hello}"
fi
#!/bin/bash
case ${1} in
"one")
echo "your choice is ONE"
;;
"two")
echo "your choice is TWO"
;;
"three")
echo "your choice is THREE"
;;
*)
echo "Usage ${0} {one|two|three}"
;;
esac
函数
#!/bin/bash
function printit()
{
echo "Your choice is ${1}"
}
echo "This program will print your selection !"
case ${1} in
"one")
printit 1
;;
"two")
printit 2
;;
"three")
printit 3
;;
*)
echo "Usage ${0} {one|two|three}"
;;
esac
for循环
简单循环
for i in 1 2 3 4 5
do
echo $i
done
参数遍历
for i
do
echo $i
done
遍历变量
for i in {1..6}
do
echo $i
done
for i in {x,y{j,k}{1,2,3},z}
do
echo $i
done
for i in $(seq 1 5)
do
echo $i
done
for i in `cat user.txt`
do
if id $i &>/dev/null ;then
echo "$i existed!"
else
echo "$i not existed!"
fi
done
for ((i=1;i<=5;i++))
do
echo $i
done