运行一个命令如果存在,否则退回到第二个命令的Shell一行代码。

huangapple go评论62阅读模式
英文:

Shell one-liner to run a command if it exists, or fall back to a second one if it doesn't

问题

我有两个需要以不同方式运行的应用程序,但我习惯于使用我的bash别名来启动它们,所以我想将它们合并。

一个命令是./bin/dev,另一个是bundle exec rails s

所以我尝试过这样做,但那不是我想要的。

./bin/dev || bundle exec rails s

这个命令会在该文件夹中找到bin/dev时启动它,但当我取消(ctrl+C)时,它会“继续”执行链并运行第二个命令。

我只希望第一个命令失败时才运行第二个命令。这可能吗(一行的bash别名)?

英文:

I have two apps who need to be ran in different ways, but I'm so used to my bash alias to start them, so I would like to combine it

One command is ./bin/dev, and another is bundle exec rails s

So I tried to do this, but that doesn't do what I want.

./bin/dev || bundle exec rails s

This one would start bin/dev if available in that folder, but when I cancel (ctrl+C), it would "continue" the chain and run the 2nd command.

I only want the 2nd command to run if the first one fails. Is this possible (one-liner bash alias)

答案1

得分: 2

Use if/else 以便仅在存在./bin/dev而不是其执行时有条件地进行操作

if [ -x ./bin/dev ]; then ./bin/dev; else bundle exec rails s; fi
英文:

Use if/else so that you only conditionalize on the existence of ./bin/dev, not its execution

if [ -x ./bin/dev ]; then ./bin/dev; else bundle exec rails s; fi

huangapple
  • 本文由 发表于 2023年5月22日 22:13:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定