S
S
Sergey2015-12-31 00:36:26
linux
Sergey, 2015-12-31 00:36:26

How to make a bash script with a parameter?

How to read the parameter passed when running the script?
For example:
bashscript.sh -name testname -ip 127.0.0.1
Of course, the order of parameters can be different:
bashscript.sh -ip 127.0.0.1 -name testname
How to count ip in $IP and name in $NAME?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey, 2015-12-31
@butteff

Here is an example syntax:

while [ $# -ne 0 ]; do
      case "$1" in
        -u)
          USER=$2
          ;;
        -p)
          PASSWORD=$2
          ;;
        -q)
          htvcenter_SERVER=$2
          ;;
        -i)
          INTERFACE=$2
          ;;
        -n)
          APPLIANCE_NAME=$2
          ;;
        -s)
          htvcenter_WEB_PROTOCOL=$2
          ;;
      esac
      shift
    done

A
Anton, 2015-12-31
@hummingbird

#!/bin/bash

showopts () {
  while getopts ":pq:" optname
    do
      case "$optname" in
        "p")
          echo "Option $optname is specified"
          ;;
        "q")
          echo "Option $optname has value $OPTARG"
          ;;
        "?")
          echo "Unknown option $OPTARG"
          ;;
        ":")
          echo "No argument value for option $OPTARG"
          ;;
        *)
        # Соответствий не найдено
          echo "Unknown error while processing options"
          ;;
      esac
    done
  return $OPTIND
}

showargs () {
  for p in "[email protected]"
    do
      echo "[$p]"
    done
}

optinfo=$(showopts "[email protected]")
argstart=$?
arginfo=$(showargs "${@:$argstart}")
echo "Arguments are:"
echo "$arginfo"
echo "Options are:"
echo "$optinfo"

./scrypt.sh -p -q qoptval abc "def ghi"
Arguments are:
[abc]
[def ghi]
Options are:
Option p is specified
Option q has value qoptval

V
Vlad Zhivotnev, 2015-12-31
@inkvizitor68sl

https://github.com/kward/shflags

O
Oleg Kleshchuk, 2016-01-07
@xenozauros

There are already beautiful examples here.
But, in short, if, then inside the script, the variables will have a value:
$1 - the first argument
$2 - the second
, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question