Specify command line arguments like name=value pairs for shell script

前端 未结 5 1158
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 07:38

Is it possible to pass command line arguments to shell script as name value pairs, something like

myscript action=build module=core

and th

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 08:28

    It's quite an old question, but still valid I have not found the cookie cut solution. I combined the above answers. For my needs I created this solution; this works even with white space in the argument's value.

    Save this as argparse.sh

    #!/bin/bash
    
    : ${1?
      'Usage:
      $0 --=" " [ --=" " | --="" ]'
    }
    
    declare -A args
    while [[ "$#" > "0" ]]; do
      case "$1" in 
        (*=*)
            _key="${1%%=*}" &&  _key="${_key/--/}" && _val="${1#*=}"
            args[${_key}]="${_val}"
            (>&2 echo -e "key:val => ${_key}:${_val}")
            ;;
      esac
      shift
    done
    (>&2 echo -e "Total args: ${#args[@]}; Options: ${args[@]}")
    
    ## This additional can check for specific key
    [[ -n "${args['path']+1}" ]] && (>&2 echo -e "key: 'path' exists") || (>&2 echo -e "key: 'path' does NOT exists");
    

    @Example: Note, arguments to the script can have optional prefix --

    ./argparse.sh --x="blah"
    ./argparse.sh --x="blah" --yy="qwert bye"
    ./argparse.sh x="blah" yy="qwert bye"
    

    Some interesting use cases for this script:

    ./argparse.sh --path="$(ls -1)"
    ./argparse.sh --path="$(ls -d -1 "$PWD"/**)"
    

    Above script created as gist, Refer: argparse.sh

提交回复
热议问题