# 脚本开发

# 一、部分方法

1、条件分支结构

if [ -d "$JAVA_HOME/bin" ] ; then
    PATH="$JAVA_HOME/bin:$PATH"
1
2

2、限定运行权限

if [ "$USER" != 'jboss1' ]; then
     echo "Sorry, this script must be run as JBOSS1!"
     exit 1
fi
echo "continue script"
1
2
3
4
5

3、根用户判别

if [ "$UID" -gt 0 ]; then
     echo "Sorry, this script must be run as ROOT!"
     exit 1
fi
echo "continue script"
1
2
3
4
5

4、带参数执行程序

$#表示参数数量

if [ $# -eq 0 ]; then
    echo "No arguments provided"
    exit 1
fi
echo "arguments found: $#"
1
2
3
4
5

5、交互输入

echo "enter a word please:"
read word
echo $word
1
2
3
read -p "Install Software ?? [Y/n]: " answ
if [ "$answ" == 'n' ]; then
    exit 1
fi
    echo "Installation starting..."
1
2
3
4
5

6、Shell中单引号和双引号区别

新建文件test.sh,内容如下:

#!/bin/bash
do_date=$1

echo '$do_date'
echo "$do_date"
echo "'$do_date'"
echo '"$do_date"'
echo `date`
1
2
3
4
5
6
7
8

执行结果

test.sh 2019-02-10
$do_date
2019-02-10
'2019-02-10'
1
2
3
4

总结: (1)单引号不取变量值 (2)双引号取变量值 (3)反引号`,执行引号中命令 (4)双引号内部嵌套单引号,取出变量值 (5)单引号内部嵌套双引号,不取出变量值

更新时间: 8/27/2021, 3:10:49 PM