Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash pass variable name as argument

I have a simple script (let's call it script.sh):

#!/bin/bash

source variables
echo $1

What I want to achieve is scripts output:

255.255.255.255

When executed like:

./script.sh VARIABLE

where VARIABLE is defined in variables file:

VARIABLE=255.255.255.255

Is it possible?

like image 596
Krzysztof Bielak Avatar asked Dec 12 '17 09:12

Krzysztof Bielak


People also ask

How to pass arguments in a bash script?

You can pass the arguments to any bash script when it is executed. There are several simple and useful ways to pass arguments in a bash script. In this article guide, we will let you know about some very easy ways to pass and use arguments in your bash scripts. Create a new file with any name using the “touch” command, e.g., “file.sh”.

How to use “@” variable in Bash?

We can use “@” variable to access every parameter passed to the script via the command line. It is a special variable that holds the array of variables in BASH. In this case, we are using it alone, so it contains the array of positional parameters passed in. We can use it to iterate over the parameters passed using loops or while loop as well.

Why does the variable name start with 1 in Bash?

Here, the variable name starts with 1 because the filename/ script name is the 0th parameter. If you have more than 9 parameters, make sure to use { } around the number as without the parenthesis, bash will only see $10 as $1 and exclude the 0, so use $ {10} and so on instead of simply $10.

How do I pass a filename as a command line argument?

Instead of prompting the user for the filename, we can make the user simply pass the filename as a command line argument while running the script as follows: The first bash argument (also known as a positional parameter) can be accessed within your bash script using the $1 variable.


2 Answers

example:

#!/bin/bash

variable=255.255.255.255
param=$1
echo ${!param}

then execute:

bash script.sh variable
255.255.255.255

The exclamation mark makes param to get the value of the variable with that name. See about parameter indirection.

like image 168
thanasisp Avatar answered Nov 01 '22 23:11

thanasisp


Could you please try following it may help you in same.

./script.sh "$VARIABLE"
like image 22
RavinderSingh13 Avatar answered Nov 02 '22 01:11

RavinderSingh13