04 参数和脚本运行

127 阅读1分钟

04 参数和脚本运行

参数的基本用法

读取参数和脚本名称

#!/bin/bash
# 脚本名称 mytest.sh
echo 脚本的名称是:$(basename $0)
echo 传入的第一个参数是:$1
echo 传入的第二个参数是:$2

# 如果传入的参数超过 9 个,往后的参数需要添加花括号
if [ -n "${10}" ]
then
    echo "传入的第十个参数是:${10}"
fi

# 判断前一行命令是否执行完成,返回 0 表示执行成功
echo -e "hello"
status=$?
if [ $status -eq 0 ]; then
    echo "Command executed successfully."
else
    echo "Command failed with status $status."
fi
# 参考执行 ./mytest.sh param01 param02

获取参数的两种方式


#!/bin/bash
# Exploring different methods for grabbing all the parameters
# $* 将所有参数看作一个整体;$@ 将每个参数看作一个独立的字符串
echo
echo "Using the \$* method: $*"
count=1
for param in "$*"
do
     echo "\$* Parameter #$count = $param"
     count=$[ $count + 1 ]
done
#
echo
echo "Using the \$@ method: $@"
count=1
for param in "$@"
do
     echo "\$@ Parameter #$count = $param"
     count=$[ $count + 1 ]
done
echo
exit

脚本执行结果参考

#执行脚本
$ ./grabdisplayallparams.sh alpha beta charlie delta 

# 输出结果

Using the $* method: alpha beta charlie delta
$* Parameter #1 = alpha beta charlie delta

Using the $@ method: alpha beta charlie delta
$@ Parameter #1 = alpha
$@ Parameter #2 = beta
$@ Parameter #3 = charlie
$@ Parameter #4 = delta

case 分支条件判断

#!/bin/bash
# Extract command-line options

while [ -n "$1" ]
do
     case "$1" in
          -a) echo "Found the -a option" ;;
          -b) echo "Found the -b option" ;;
          -c) echo "Found the -c option" ;;
          *) echo "$1 is not an option" ;;
     esac
     shift
done

获取用户输入

read -p "输入一个参数:"
if [$# -eq 1] # 判断参数个数是否为 1
then
     echo 你输入的参数是:$REPLY
else
     echo 输入一个参数

read -p "请输入你的年龄:" age
echo 你已经 $age 岁了

if read -t 5 -p "Enter your name: " name # 五秒等待时间
then
     echo "你的名字是: $name"
else
     echo
     echo "已超时,自动退出"
fi

read -s -p "Enter your password: " pass
echo "Your password is $pass"

脚本后台运行的三种方式

  1. 使用 & 符号

    # 后台运行并将输出内容覆盖添加到 output.log
    # 此方法运行后会打印进程作业号和 pid
    ./demo.sh >output.log &
    
  2. 使用 nohup

    # 此方法不会输出 pid,可使用 ps aux | grep demo.sh 找出进程并结束
    nohup ./demo.sh > output.log &
    
    
  3. 使用 crontab

    0 0 * * * /opt/script/demo.sh # 每天零点运行脚本
    
    30 16 * * 1,3 /opt/script/demo.sh # 每周一和周三的 16:30 运行脚本
    
    10 8 7 * * /opt/script/demo.sh # 每个月的七号 8:10 运行脚本
    
    0 0 15 6,12 * /opt/script/demo.sh # 每年 6 月和 12 月的 15 号零点执行脚本
    
    0 0 L * * /opt/script/demo.sh # 每个月的最后一天零点执行脚本
    
    0 0 * * 5L /opt/script/demo.sh # 每个月的最后一个星期五执行脚本