Tony B
Tony B

Reputation: 1

Bash Scripting - User Input a Command

Very easy question but I really can't find this when I Google. Sorry! I'm trying to write a script that runs a user's command that he or she enters but I can't run the command that the user enters.

#!/bin/bash
echo -e "Enter a Command: "
read $COMMAND
echo "Output: $COMMAND"  # I can't figure how to implement and print the command

Enter a Command: ls Output: folder1 folder2 folder3 test.txt)

Upvotes: 0

Views: 1429

Answers (3)

Tony B
Tony B

Reputation: 1

Thanks! This answered my question:

#!/bin/bash echo -e "Enter a Command: " read COMMAND echo Output: eval "$COMMAND"

Upvotes: 0

Mostafa Hassan
Mostafa Hassan

Reputation: 298

All you need is to delete the dollar sign from the read command

#!/bin/bash
echo "Enter a Command: "
read COMMAND
echo "Output: $COMMAND" 

Happy scripting!, please don't forget to marked as answered ;)

Upvotes: 1

Barmar
Barmar

Reputation: 780688

Use eval to execute a command from a variable.

Also, you don't put $ before the variable name in the read command. That's only used when you want to get the variable's value.

#!/bin/bash
echo -e "Enter a Command: "
read COMMAND
echo Output:
eval "$COMMAND"

DEMO

Upvotes: 0

Related Questions