Myrddin Emrysf
Myrddin Emrysf

Reputation: 11

Linux shell script "read" command

So, I'm new to scripting, and I'm having some problems. The command I need to execute is:

read -p Enter_the_DEVICE_Bssid "device1" ; 
read -p Enter_the_DEVICE_Bssid "device2" ; 
read -p Enter_the_DEVICE_Bssid "device3"

That command works, but when I set it as a variable ie:

com="read -p Enter_the_DEVICE_Bssid "device1" ; 
read -p Enter_the_DEVICE_Bssid "device2" ; 
read -p Enter_the_DEVICE_Bssid "device3"" 

and execute it as: $com it does not work. Probably because the read command is trying to set my input to the variables device1 and ; . Any ideas on how to fix it?

Upvotes: 1

Views: 5468

Answers (2)

Sriharsha Kalluru
Sriharsha Kalluru

Reputation: 1823

You are not completing the quotes.

 com="read -p Enter_the_DEVICE_Bssid "device1"

Quotes always look for a pair and you are missing that.

> com="read -p Enter_the_DEVICE_Bssid:  device1"
> $com
Enter_the_DEVICE_Bssid:abc123
> echo $device1
abc123

Here I am using bash shell.

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263617

You're running into problems with the order in which things are expanded by the shell.

A simpler example:

$ command='echo one ; echo two'
$ $command
one ; echo two

The semicolon in the value of $command is taken as part of the argument to echo, not as a delimiter between two echo commands.

There might be a way to resolve this so it works the way you want, but why bother? Just define a shell function. Using my simple example:

$ command() { echo one ; echo two ; }
$ command
one
two
$ 

Or using yours:

com() {
    read -p "Enter_the_DEVICE_Bssid: " device1
    read -p "Enter_the_DEVICE_Bssid: " device2
    read -p "Enter_the_DEVICE_Bssid: " device3
}

Note that I've added ": " at the end of the prompts. I've also removed the unnecessary semicolons and the quotation marks around the variable names (since the argument has to be a valid variable name, it doesn't need to be quoted).

Upvotes: 3

Related Questions