2022/06/10

Shell Script With Optional Arguments

我們在操作 Linux 上的 script 時,常常會使用一些 optional arguments,例如:

ls -l
grep -iR --include *.php

我們自己製作腳本時可以使用 getopts 以及 shift 達到這樣的效果,以一個安裝系統的腳本舉例。

install.sh

#/bin/bash

install_nginx=0
install_mysql=0
nginx_port=80
mysql_port=3306

while getopts "nmP:p:" OPTION; do
  case "$OPTION" in
  n)
    install_nginx=1
    ;;
  m)
    install_mysql=1
    ;;
  p)
    nginx_port="$OPTARG"
    ;;
  P)
    mysql_port="$OPTARG"
    ;;
  esac
done

echo "Install basic"

if [ "$install_nginx" == 1 ]; then
  echo "Install nginx with port $nginx_port"
fi

if [ "$install_mysql" == 1 ]; then
  echo "Install mysql with port $mysql_port"
fi
bash install.sh

# Install basic

bash install.sh -n

# Install basic
# Install nginx with port 80

bash install.sh -n -p 8888 -m
# Install basic
# Install nginx with port 8888
# Install mysql with port 3306

上面的方法只能帶入單一字符,所以像是 port 這種常見共用的文字只能用大小寫或者不同字符取代,彈性比較少,使用 shift 可以解決這個問題。

#/bin/bash

install_nginx=0
install_mysql=0
nginx_port=80
mysql_port=3306

while [ "$1" != "" ]; do
  case "$1" in
  --nginx)
    install_nginx=1
    ;;
  --nginx-port)
    shift
    nginx_port="$1"
    ;;
  --mysql)
    install_mysql=1
    ;;
  --mysql-port)
    shift
    mysql_port="$1"
    ;;
  esac
  shift
done

echo "Install basic"

if [ "$install_nginx" == 1 ]; then
  echo "Install nginx with port $nginx_port"
fi

if [ "$install_mysql" == 1 ]; then
  echo "Install mysql with port $mysql_port"
fi
bash install.sh --nginx
# Install basic
# Install nginx with port 80

bash install.sh --nginx --nginx-port 8888
# Install basic
# Install nginx with port 8888

bash install.sh --nginx --mysql --mysql-port 3307
# Install basic
# Install nginx with port 80
# Install mysql with port 3307

reference

沒有留言:

張貼留言