Pattern expansion to run commands

被刻印的时光 ゝ 提交于 2019-12-02 05:04:25

问题


Knowing I am able to run echo or mv to expand patterns like these: echo {0..9}{A..Z}. I am curious to know if there is a way to do the same but to run commands?

docker-compose {stop,rm,up -d}

The example above does not work, but there is some way to accomplish that (to run stop, rm and up separately)?


回答1:


You can use eval:

eval docker-compose\ {stop,rm,'up -d'}\;

Careful escaping/quoting is needed, though. Just test with echo instead of docker that it emits the correct commands:

$ echo docker-compose\ {stop,rm,'up -d'}\;
docker-compose stop; docker-compose rm; docker-compose up -d;



回答2:


Not the way you mention it.

Brace expansion occurs before any other expansion. This means that when you say echo {0,1}{a,b}, Bash expands the braces before going through any other step. This way, it becomes echo 0a 0b 1a 1b, a single command.

When you mention docker-compose {stop,rm,up -d}, note this would expand to a single command: docker-compose stop rm up -d, which doesn't seem to be valid.

It looks like you would like to run three different commands:

docker-compose stop
docker-compose rm
docker-compose up -d

For this, you may want to use a loop (note "up -d" is quoted so that it is treated as a single argument):

for argument in stop rm "up -d"
do
    docker-compose $argument
done


来源:https://stackoverflow.com/questions/33733430/pattern-expansion-to-run-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!