bvz
bvz

Reputation: 879

Create alias from stdout

I am trying to dynamically create alias' from the output of another command line tool.

For example:

> MyScript
blender="/opt/apps/blender/blender/2.79/blender"
someOtherAlias="ls -l"

I am trying the following code:

MyScript | {
   while IFS= read -r line;
   do
      `echo alias $line`;
   done;
}

But when I run this, I get the following error:

bash: alias: -l": not found

Just trying to run this command by itself gives me the same error:

> `echo 'alias someOtherAlias="ls -l"'`
bash: alias: -l": not found

But obviously the following command does work:

alias someOtherAlias="ls -l"

I've tried to find someone else who may have done this before, but none of my searches have come up with anything.

I would appreciate any and all help. Thanks!

Upvotes: 0

Views: 196

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

See how bash (and posix shells) command parsing and quoting works and see difference between syntax and literal argument: for example '.."..' "..'.." are litteral quotes in an argument whereas " or ' are shell syntax and are not part of argument

also, enabling tacing with set -x may help to understand :

set -x
`echo 'alias someOtherAlias="ls -l"'`
++ echo 'alias someOtherAlias="ls -l"'
+ alias 'someOtherAlias="ls' '-l"'
bash: alias: -l": not found

bash sees 3 words : alias, someOtherAlias="ls and -l". and alias loops over its arguments if they contain a = it create an alias otherwise it displays what alias argument is as -l" is not an alias it shows the error.

Note also as backquotes means command is run in a subshell (can be seen with mutiple + in trace) it will have no effect in current shell.

eval may be use to reinterpret literal as bash syntax (or to parse again a string).

So following should work, but be careful using eval on arbitrary arguments (from user input) can run arbitrary command.

eval 'alias someOtherAlias="ls -l"'

Finally also as bash commands after pipe are also run in subshell.

while IFS= read -r line;
do
    `echo alias $line`;
done <MyScript

Upvotes: 1

Related Questions