0

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)

0

3 Answers 3

1

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 ;)

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

2 Comments

As a general rule, in shell syntax you use $ to get the value of a variable, not to set the value. So you don't use $ when reading into a variable, assigning to it with =, etc.
You never use $ to set the value of a variable. read, however, takes the name of a variable as its argument, which can be the result of a parameter expansion. COMMAND=foo; read $COMMAND is equivalent to read foo.
0

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

3 Comments

Thanks! I tried this but nothing output'd to my screen:
#!/bin/bash echo -e "Command: " read $COMMAND eval "$COMMAND"
read $COMMAND should be read COMMAND
0

Thanks! This answered my question:

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

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.