user3627319
user3627319

Reputation: 425

How to pass shell variables as Command Line Argument to a shell script

I have tried passing the shell variables to a shell script via command line arguments.

Below is the command written inside the shell script.

LOG_DIRECTORY="${prodName}_${users}users"
mkdir -m 777 "${LOG_DIRECTORY}"

and m trying to run this as:

prodName='DD' users=50 ./StatCollection_DBServer.sh

The command is working fine and creating the directory as per my requirement. But the issue is I don't want to execute the shell script as mentioned below.

Instead, I want to run it like

DD 50 ./StatCollection_DBServer.sh

And the script variables should get the value from here only and the Directory that will be created will be as "DD_50users".

Any help on how to do this?

Thanks in advance.

Upvotes: 11

Views: 27902

Answers (3)

Thawn
Thawn

Reputation: 805

Bash scripts take arguments after the call of the script not before so you need to call the script like this:

./StatCollection_DBServer.sh DD 50

inside the script, you can access the variables as $1 and $2 so the script could look like this:

#!/bin/bash
LOG_DIRECTORY="${1}_${2}users"
mkdir -m 777 "${LOG_DIRECTORY}"

I hope this helps...

Edit: Just a small explanation, what happened in your approach:

prodName='DD' users=50 ./StatCollection_DBServer.sh

In this case, you set the environment variables prodName and users before calling the script. That is why you were able to use these variables inside your code.

Upvotes: 10

BigBang
BigBang

Reputation: 149

Simple call it like this: sh script.sh DD 50

This script will read the command line arguments:

prodName=$1
users=$2
LOG_DIRECTORY="${prodName}_${users}users"
mkdir -m 777 "$LOG_DIRECTORY"

Here $1 will contain the first argument and $2 will contain the second argument.

Upvotes: 2

Hasan
Hasan

Reputation: 1895

#!/bin/sh    
prodName=$1
users=$2
LOG_DIRECTORY="${prodName}_${users}users"
echo $LOG_DIRECTORY
mkdir -m 777 "$LOG_DIRECTORY"

and call it like this :

chmod +x script.sh
./script.sh DD 50

Upvotes: 5

Related Questions