Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 674
user3627319 Avatar asked Dec 20 '22 09:12

user3627319


1 Answers

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.

like image 145
Thawn Avatar answered May 06 '23 23:05

Thawn