11

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.

1
  • You can't do it in the manner that you want. Bash doesn't work that way. Bash will look at the first word, 'DD', and think that is the command and every word after that is the argument to DD. You need to follow Ansurul's suggestion, or do something funny like making DD your shell script. Commented Nov 24, 2014 at 12:57

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

if that was the correct answer to your question, please accept it. Thanks!
Yes @ Thawn, implemented your suggestion. Now it's working fine. Thank You. :-)
5
#!/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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.