'Fish shell - advanced control flow
Normally, fish shell processes commands like this:
1 && 3 (2)
This is perfectly useful and it mirrors the order of execution that I would want most of the time.
I was wondering if a different syntax exists to get a slightly different order of execution?
Sometimes I want this:
2 && 3 (1)
is that possible without using multiple lines ?
This is a trivial example:
cd ~ && cat (pwd | psub)
In this example I want to run pwd
first then run cd
and then run cat
edit: oh! This seems to work:
cat (pwd | psub && cd ~)
Solution 1:[1]
This is one of those cases where I'm going to recommend just using multiple lines [0].
It's cleaner and clearer:
set -l dir (pwd)
cd ~ && cat (printf '%s\n' $dir | psub)
This is completely ordinary and straightforward, and that's a good thing. It's also easily extensible - want to run the cd
only if the pwd
succeded?
set -l dir (pwd)
and cd ~ && cat (printf '%s\n' $dir | psub)
as set
passes on the previous $status, so here it passes on the status of pwd
.
The underlying philosophy here is that fish script isn't built for code golf. It doesn't have many shortcuts, even ones that posix shell script or especially shells like bash and zsh have. The fish way is to simply write the code.
Your answer of
cat (pwd | psub && cd ~)
doesn't work because that way the cat
is no longer only executed if the cd
succeeds - command substitutions can fail. Instead the cd
is now only done if the psub
succeeded - notably this also happens if pwd
fails.
(of course that cat (pwd | psub)
is fairly meaningless and could just be pwd
, I'm assuming you have some actual code you want to run like this)
[0]: Technically this doesn't have to be multiple lines, you can write it as set -l dir (pwd); cd ~ && cat (printf '%s\n' $dir | psub)
. I would, however, also recommend using multiple lines
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | faho |