What is the correct way to call some command stored in variable?
Are there any differences between 1 and 2?
#!/bin/sh
cmd="ls -la $APPROOTDIR | grep exception"
#1
$cmd
#2
eval "$cmd"
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the Bash man page):
Using
$cmddirectly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.Using
eval "$cmd"does nothing until the quote removal phase, where$cmdis returned as is, and passed as a parameter toeval, whose function is to run the whole chain again before executing.So basically, they’re the same in most cases and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion: