Process options from command line in BASH

26 篇文章 0 订阅
25 篇文章 0 订阅

Have you ever met thus kind of requirement:

Use BASH to write a script with options to implements some functions??

For example, here is the requirement.. "We need a script in BASH to get its options and save them into environments for further using. options include -h, -n name, -v version, -r release, -o output. And the output should be like the followings:"

[xiaoqiang@Linux01:~/bin] $./get_args.sh
[xiaoqiang@Linux01:~/bin] $./get_args.sh -h
./get_args.sh -n name -v version -r release -o output
[xiaoqiang@Linux01:~/bin] $./get_args.sh -n Xiaoqiang -v 1.0 -r 01 -o ~/
GETARGS_NAME=Xiaoqiang
GETARGS_OUTPUT=/home/xiwang/
GETARGS_RELEASE=01
GETARGS_VERSION=1.0

Now, the script you may needed:

#!/bin/bash
#
# Example of getting arguments from command line.
#

# get_args.sh, 2012-06-08 T1256

#
# for example:
# ./get_args.sh -h
# ./get_args.sh -n name -v version -r release -o output
#

while [ $# -ne 0 ]; do
  case "$1" in
    -h|--help)
      echo "./get_args.sh -n name -v version -r release -o output"
      exit 0
      ;;
    -n|--name)
      GETARGS_NAME="$2"; export GETARGS_NAME
      shift; shift;
      ;;
    -v|--version)
      GETARGS_VERSION="$2"; export GETARGS_VERSION
      shift; shift;
      ;;
    -r|--release)
      GETARGS_RELEASE="$2"; export GETARGS_RELEASE
      shift; shift;
      ;;
    -o|--output)
      GETARGS_OUTPUT="$2"; export GETARGS_OUTPUT
      shift; shift;
      ;;
    *)
      echo "Error, no such option or argument not supported."
      exit 1
      ;;
  esac
done

set | grep GETARGS_




                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值