Tags: basic, build, building, command, commands, dynamic, dynamically, eval, examplei, explain, files, linux, programming, retreive, shell, unix, users
Building dynamic commands with eval
On Programmer » Unix & Linux
2,062 words with 1 Comments; publish: Wed, 30 Apr 2008 17:24:00 GMT; (20062.50, « »)
Hi all shell users,
I'd like to build a command dynamically using eval.
Let me explain with a basic example:
I want to retreive the last "n" files from the current directory:
bash-2.05$ command="ls -al $opts"
bash-2.05$ opts="| tail -1"
bash-2.05$ eval $command
drwxrwxrwx 7 euclide5 staff 512 Dec 21 14:47 myfile.txt
So far so good, eval translated $opts into "| tail -1"
Now what if inside my shell script I want to retrieve the last 2 lines ?
bash-2.05$ opts="| tail -2"
Unfortunately I don't get what expected, but still the last line:
bash-2.05$ eval $command
drwxrwxrwx 7 euclide5 staff 512 Dec 21 14:47 myfile.txt
What can I do to refresh the value of the variable $opts so that
I can change the parameters dynamically ?
Thanks a lot
Francesco
http://unix-linux.itags.org/q_unix-linux-programming_78173.html
All Comments
Leave a comment...
- 1 Comments

- "qazwart" <qazwart.unix-linux.itags.org.gmail.com> wrote in message news:<1112379521.249958.154510.unix-linux.itags.org.z14g2000cwz.g
ooglegroups.com>...
> The problem is that the value of $command doesn't change when $opts
> changes. I tried using single quotes when setting command like this:
> $ command='ls -al $opts'
> $ opts='| tail -2'
> $ eval $command
> |; No such file or directory
> tail: No such file or directory
> -2: No such file or directory
> Setting -vx helped showed what was going on:
> $ set -vx
> $ eval $command
> eval "$command"
> + eval 'ls -al $opts'
> /bin/ls -al $opts
> ++ /bin/ls -al '|' tail -3
> |: No such file or directory
> tail: No such file or directory
> -3: No such file or directory
> This showed that $command was correctly expanding as "ls -al | tail
> -2", but the "ls" command is interpreting the pipe as a literal
> character instead of a shell pipe. To get around this problem, I had to
> do this:
> $ eval $(eval "echo $command")
Thank you. It works great.
regards
Francesco
#1; Wed, 30 Apr 2008 17:25:00 GMT