user6348718
user6348718

Reputation: 1395

How to pass parameters using command line arguments in shell script

I am new to shell script and I am working on shell scripting for jmeter. So far to run a jmeter script, I have written my shell script like below:

#! bin/sh    
start(){
    echo "Please enter the file name .jmx extension"
    read file

echo "Please enter the log file name .jtl extension"
read log_file

jmeter.sh -n -t $file -l $log_file
}
while [ "$1" != "" ]; do
case "$1" in
        start )
            start
            ;;
         *)
            echo $"Usage: $0 {start|stop}"
            exit 1
        esac
   shift
done

I have a stop method to terminate the process. Here, for this script I am asking the user to enter the .jmx fileName and .jtl fileName in different lines. But I want the user to be able to pass the .jmx fileName and .jtl fileName at the time he types the command to execute the script.

example: $ ./script.sh .jmx fileName .jtl fileName then, the script should run.

I don't know how to do it. Can someone please help?

Upvotes: 3

Views: 2818

Answers (1)

glenn jackman
glenn jackman

Reputation: 247102

Since read reads from stdin, you need to pass the filenames on stdin:

{ echo "file.jmx"; echo "file.jtl"; } | ./script.sh start

Using a here-document can be tidier:

./script.sh start <<END_INPUT
file.jmx
file.jtl
END_INPUT

A bit of code review: if the usage only takes a single parameter, "start" or "stop", you don't need the while loop:

#!/bin/sh

do_start_stuff() { ... }
do_stop_stuff() { ... }

case "$1" in 
    start) do_start_stuff;;
    stop)  do_stop_stuff;;
    *)     echo "Usage: $0 {start|stop}"; exit 1;;
esac

To rewrite your script to take all the parameters:

#!/bin/sh

usage() {
    echo "Usage $0 {start ...|stop}"
    # provide more info about arguments for the start case
    # provide an example usage
}

case "$1" in 
    stop) do_stop_stuff ;;
    start)
        shift
        if [ "$#" -ne 4 ]; then usage; exit 1; fi
        jmeter.sh -n -t "$1" "$2" -l "$3" "$4"
        ;;
    *) usage ;;
esac

Upvotes: 1

Related Questions