working on it ...

Filters

Explore Public Snippets

Sort by

Found 92 snippets matching: getopt

    public by david-e  2869  15  5  0

    Bash getops example

    Simple example of argument parsing with getopts
    #!/bin/bash                                                                                                 
    usage()
    {   
        echo ""
        echo "$0 -f <csv|html> -i <IP address> -l"
        echo ""
        echo "Example:"
        echo " $0 -f html -i 172.16.88.83"
        echo " $0 -f csv  -i 172.16.88.83 -l"
    }
    
    #default value                                                                                              
    FORMAT="csv"
    IPADDR=""
    LOAD=false
    while getopts ":f:i:l" optname
    do  
        case "$optname" in
            "f")
                if [[ ${OPTARG} == "csv" || ${OPTARG} == "html" ]] ; then
                    FORMAT="${OPTARG}"
                else
                    echo "Output format not supported"
                    usage
                    exit 1
                fi
                ;;
            "i")
                IPADDR="${OPTARG}"
                ;;
            "l")
                LOAD=true
                ;;
            "?")
                usage
                exit 1
                ;;
            ":")
                echo "No argument value for option $OPTARG"
                ;;
            *)
                echo "Unknown error while processing options"
                ;;
        esac
    done
    
    # Mandatory arguments                                                                                       
    if [[ -z ${FORMAT} ]] || [[ -z ${IPADDR} ]]
    then
        usage
        exit 1
    fi
    
    echo "format: $FORMAT"
    echo "ipaddr: $IPADDR"
    if [[ ${LOAD} == "true" ]] ; then
        echo "load: true"
    else
        echo "load: false"
    fi
    

    public by msdn  1166  0  6  0

    GetOptionName

    using System;
    using System.IO;
    using System.Linq;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Reflection;
    using System.ComponentModel;
    
    static string GetOptionName(FieldInfo field)
    {
        var nameAttribute = GetAttribute<NameAttribute>(field);
    
        if (nameAttribute != null)
        {
            return nameAttribute.Name;
        }
        else
        {
            return field.Name;
        }
    }

    external by Go Sato  2  0  1  0

    いまいちよく分かっていない getopt に関するメモ.環境変数 GETOPT_COMPATIBLE がセットされている場合どんな動きになるのか? メリット・デメリットは? などなど.書きかけ

    いまいちよく分かっていない getopt に関するメモ.環境変数 GETOPT_COMPATIBLE がセットされている場合どんな動きになるのか? メリット・デメリットは? などなど.書きかけ: study_getopt.sh
    #!/bin/bash
    
    # 参考
    # getoptコマンド(コマンドラインのオプションを解析する) : JP1/Advanced Shell http://itdoc.hitachi.co.jp/manuals/3021/3021313330/JPAS0337.HTM
    
    # 形式1
    #
    #     条件 (OR)
    #         - 引数の最初のパラメーターが「-」で始まっていない場合
    #         - 環境変数GETOPT_COMPATIBLEが設定されている場合
    #
    #     コマンド形式
    #         - getopt 解析するオプション 解析される引数
    #
    #     メモ
    #         - 一番単純なのでは? ただし getopt のオプションを利用できない.
    #
    # 形式2
    #
    #     条件 (OR)
    #         - 形式1の条件に合致しない.
    #         - -o オプションが指定されていない.
    #
    #     コマンド形式
    #         - getopt [オプション] [--] 解析するオプション 解析される引数
    #
    #     メモ
    #         - ショートオプションはいらないが,getopt のオプションを使用したい場合にこれ?
    #
    # 形式3
    #
    #     条件 (OR)
    #         - 形式1の条件に合致しない.
    #         - -o オプションが指定されている.
    #
    #     コマンド形式
    #         - getopt [オプション] -o 解析するショートオプション名 [オプション] [--] 解析される引数
    #
    #     メモ
    #         - ショートオプションを使用したい場合,形式3のみが選択肢となる.
    
    # 形式1
    OPT=`getopt help,list:,protocol:,region:,service: "$@"`
    
    # 形式2
    OPT=`getopt -- help,list:,protocol:,region:,service: "$@"`
    
    # 形式3
    OPT=`getopt -o hl:p:r:s: --long help,list:,protocol:,region:,service: -- "$@"`
    
    if [ ${?} != 0 ] ; then
        echo 'Error !!'
    fi
    eval set -- "${OPT}"
    
    echo "${OPT}"
    
    
    

    external by dgoguerra  69  0  1  0

    getopt handmade alternative in bash, supporting short and long options

    getopt handmade alternative in bash, supporting short and long options: script-with-options.sh
    #!/bin/bash
    
    usage() {
    	echo "Script description"
    	echo
    	echo "Usage: script-name.sh -i <input-file> -o <output-file> [options]..."
    	echo
    	echo "Options:"
    	echo
    	echo "  -h, --help"
    	echo "      This help text."
    	echo
    	echo "  -i <file>, --input <file>"
    	echo "      Input file. If \"-\", stdin will be used instead."
    	echo
    	echo "  -o <file>, --output <file>"
    	echo "      Output file."
    	echo
    }
    
    while [ "$#" -gt 0 ]
    do
    	case "$1" in
    	-h|--help)
    		usage
    		exit 0
    		;;
    	-i|--input)
    		input="$2"
    
    		# Jump over <input-file>, in case "-" is a valid input file 
    		# (keyword to standard input). Jumping here prevents reaching
    		# "-*)" case when parsing <input-file>
    		shift
    		;;
    	-o|--output)
    		output="$2"
    		;;
    	-*)
    		echo "Invalid option '$1'. Use --help to see the valid options" >&2
    		exit 1
    		;;
    	# an option argument, continue
    	*)	;;
    	esac
    	shift
    done
    
    # script content!
    
    

    external by 7heo  45  0  1  0

    getopt implementation in shell

    getopt implementation in shell: getopt
    parseFlag () {
      case "$1" in
        "f")
          echo "Flag f set"
          ;;
      esac
    }
    
    while [ "${1:0:1}" = "-" ]
    do
      case "${1:1:1}" in
        "-")
          shift
          break
          ;;
        *)
          parseFlag "${1:1:1}"
          ;;
      esac
      [ "${1:1:1}" = "${1:1}" ] && shift || set -- "-${1:2}" "${@:2}"
    done
    
    echo "Non-flag arguments: $@"
    
    
    

    external by jaypeche  11  1  1  0

    getopt POSIX for clamav-realtime.c

    getopt POSIX for clamav-realtime.c: hello_world.c
    C
    #include <stdio.h>
    #include <stdlib.h>
    #include <getopt.h>
    
    /* Define version */
    static const char version[] = "0.0.3";
    
    /* Flag set by ‘--verbose’. */
    static int verbose_flag;
    /*
    * Show brief command usage help:
    */
    static void print_usage() {
    fputs("Usage: [hvVCdlp] [-h | --help] [-v | --verbose] [-V | --version] [-C | --config CONFIG_PATH] [-d | --directory DIRECTORY_TARGET] [-l | --log LOGFILE] [-p | --pid PIDFILE]\n",stderr);
    fputs("\t-h (or --help)\t\t\tGives this help display\n",stderr);
    fputs("\t-v (or --verbose)\t\tBe verbose\n",stderr);
    fputs("\t-V (or --version)\t\tDisplays program version.\n",stderr);
    fputs("\t-C (or --config=CONFIGFILE)\tSetup configuration file path\n",stderr);
    fputs("\t-d (or --directory=DIRECTORY_TARGET)\tSetup target directory\n",stderr);
    fputs("\t-l (or --log=LOGFILE)\t\tSetup log file path\n",stderr);
    fputs("\t-p (or --pid=PIDFILE)\t\tSetup PID path\n",stderr);
    }
    
    int
    main (int argc, char **argv)
    {
      int c;
    
      while (1)
        {
          static struct option long_options[] =
            {
              /* These options set a flag. */
              {"verbose", no_argument, &verbose_flag, 1}, /* verbose flag set */
              {"help", no_argument, 0, 'h'},
              {"version", no_argument, 0, 'V'},
              /* These options don’t set a flag.
                 We distinguish them by their indices. */
              {"config",  required_argument, 0, 'C'},
              {"directory",  required_argument, 0, 'd'},
              {"log",    required_argument, 0, 'l'},
              {"pid",  required_argument, 0, 'p'},
              {0, 0, 0, 0}
            };
          /* getopt_long stores the option index here. */
          int option_index = 0;
    
          c = getopt_long (argc, argv, "C:d:l:p:hvV",
                           long_options, &option_index);
    
          /* Detect the end of the options. */
          if (c == -1)
            break;
    
          switch (c)
            {
            case 0:
              /* If this option set a flag, do nothing else now. */
              if (long_options[option_index].flag != 0)
                break;
              printf ("option %s", long_options[option_index].name);
              if (optarg)
                printf (" with arg %s", optarg);
              printf ("\n");
              break;
    
            case 'C':
              printf ("set config from `%s'\n", optarg);
              break;
    
            case 'd':
              printf ("set directory target to `%s'\n", optarg);
              break;
    
            case 'h':
             print_usage();
    	 break;
    
            case 'l':
              printf ("set log path to `%s'\n", optarg);
              break;
    
            case 'p':
              printf ("set pid path to `%s'\n", optarg);
              break;
    	case 'v':
    	  printf ("Be verbose \n");
    	  int verbose_flag = 1;
    	  if (verbose_flag)
    	  puts ("verbose flag is set");
    	  break;
    
            case 'V':
    	  fprintf (stderr,"This is clamav-realtime version %s\n",version);
              break;
    
            case '?':
              /* getopt_long already printed an error message. */
              break;
    
            default:
    	  print_usage();
              abort ();
            }
        }
    
      /* Instead of reporting ‘--verbose’
         and ‘--brief’ as they are encountered,
         we report the final status resulting from them. */
      // if (verbose_flag)
      //  puts ("verbose flag is set");
    
      /* Print any remaining command line arguments (not options). */
      if (optind < argc)
        {
          printf ("non-option ARGV-elements: ");
          while (optind < argc)
            printf ("%s ", argv[optind++]);
          putchar ('\n');
        }
      exit (0);
    }
    
    
    
    

    external by Averroes  11  0  1  0

    getopt gnu

    getopt gnu: getopt_gnu.py
    #!/usr/bin/env python
    """More complete example which parses and uses the options.
    """
    #end_pymotw_header
    
    import getopt
    import sys
    
    version = '1.0'
    verbose = False
    output_filename = 'default.out'
    
    print 'ARGV      :', sys.argv[1:]
    
    try:
        options, remainder = getopt.gnu_getopt(
            sys.argv[1:],
            'o:v',
            ['output=', 
             'verbose',
             'version=',
             ])
    except getopt.GetoptError as err:
        print 'ERROR:', err
        sys.exit(1)
        
    print 'OPTIONS   :', options
    
    for opt, arg in options:
        if opt in ('-o', '--output'):
            output_filename = arg
        elif opt in ('-v', '--verbose'):
            verbose = True
        elif opt == '--version':
            version = arg
    
    print 'VERSION   :', version
    print 'VERBOSE   :', verbose
    print 'OUTPUT    :', output_filename
    print 'REMAINING :', remainder
    
    
    

    external by madmax28  436  0  3  0

    Example usage of getopt in bash

    Example usage of getopt in bash: getopt.sh
    verbose=0
    some_arg="default"
    
    OPTIND=1    # getopt stores option index here
    # "hva:" is the optstring. character with : require an argument
    while getopts "hva:" opt; do
        case "$opt" in
            h)
                # print_usage
                exit 0
                ;;
            v)
                verbose=1
                ;;
            a)
                some_arg=$OPTARG
                ;;
            ?)
                # unrecognized option
                # print_usage
                exit 1
        esac
    done
    shift $((OPTIND-1))
    [ "$1" = "--" ] && shift
    
    

    external by kruton  311  0  3  0

    Fix OpenSSH Apple Keychain getopt

    Fix OpenSSH Apple Keychain getopt: gistfile1.txt
    diff --git a/ssh-add.c b/ssh-add.c
    index 10c968a..84f24d6 100644
    --- a/ssh-add.c
    +++ b/ssh-add.c
    @@ -457,7 +457,7 @@ main(int argc, char **argv)
     		    "Could not open a connection to your authentication agent.\n");
     		exit(2);
     	}
    -	while ((ch = getopt(argc, argv, "kKlLcdDxXe:s:t:")) != -1) {
    +	while ((ch = getopt(argc, argv, "kKlLcdDxXmMe:s:t:")) != -1) {
     		switch (ch) {
     		case 'k':
     			key_only = 1;
    
    

    external by 17twenty  295  0  3  0

    Decided that getopt sucked so rolled my own. Meets spec!

    Decided that getopt sucked so rolled my own. Meets spec!: demo_opts.c
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <time.h>
    #include <string.h>
    
    #define MAX_FLAG_LENGTH 20
    typedef int (*fn_pointer_t)(void *data);
    
    // We flag -> callback structure.
    struct optionFunc {
        char optflag[MAX_FLAG_LENGTH];
        fn_pointer_t callback;
    };
    
    int show_usage(void *data) {
        printf("THIS IS show_usage!\n");
        return 0;
    }
    
    int request_status(void *data) {
        printf("THIS IS request_status!\n");
        return 0;
    }
    
    int request_group(void *data) {
        printf("THIS IS request_group!\n");
        return 0;
    }
    
    int join_group(void *data) {
        if (data == NULL) {
            printf("Please specify a callgroup\n");
            return -1;
        }
    
        int group = strtol((char *)data, NULL, 10);
        printf("THIS IS join_group %d!\n", group);
        return 0;
    }
    
    int get_token(void *data) {
        printf("THIS IS get_token!\n");
        return 0;
    }
    
    int release_token(void *data) {
        printf("THIS IS release_token!\n");
        return 0;
    }
    
    int reload_config(void *data) {
        printf("THIS IS reload_config!\n");
        return 0;
    }
    
    int save_config(void *data) {
        printf("THIS IS save_config!\n");
        return 0;
    }
    
    struct optionFunc g_option_table[] = {
        { "--help", show_usage },
        { "--get-status", request_status },
        { "--get-group", request_group },
        { "--join", join_callgroup },
        { "--get-token", get_token },
        { "--release-token", release_token },
        { "--save-config", reload_config },
        { "--load-config", save_config },
    };
    #define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))
    #define MAX_OPTIONS NELEMS(g_option_table)
    
    int main(int argc, char **argv)
    {
        int option = 0; // Defaults to usage
        void *data = NULL;
    
        // Handle command line arguments
        for (int i = 1; i < argc; ++i) {
            for (int j = 0; j < MAX_OPTIONS; ++j) {
                if (strcmp(argv[i], g_option_table[j].optflag) == 0) {
                    // We found our option - if there's an operand, grab it as a parameter for option
                    option = j;
                    if (i < argc) {
                        data = argv[i + 1];
                    }
                    break;
                }
            }
        }
    
        return g_option_table[option].callback(data);
    }
    
    
    • Public Snippets
    • Channels Snippets