Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Post History

60%
+1 −0
Q&A A shell script that can run under different shells

I came up with three methods. Exit early Use exit early instead of the elif syntax. Basically shell is an interpreter. As soon as the parsing of the first if statement is finished, it will be e...

posted 2y ago by mjy‭

Answer
#1: Initial revision by user avatar mjy‭ · 2022-03-18T18:09:53Z (over 2 years ago)
I came up with three methods.


### Exit early

Use `exit` early instead of the `elif` syntax.
Basically shell is an interpreter.
As soon as the parsing of the first `if` statement is finished, it will be executed.
In this case, if shell is bash, `exit` before the parsing of the next `if` statement begins. 

```sh
if [ -n "$BASH_VERSION" ]; then
    for f in *; do echo __BASH__ $f; done
    exit
fi

if [ -n "$ZSH_VERSION" ]; then
    for f (*) echo __ZSH__ $f
fi
```


### Eval string

Use `eval`.

```sh
if [ -n "$BASH_VERSION" ]; then
    for f in *; do echo __BASH__ "$f"; done
elif [ -n "$ZSH_VERSION" ]; then
    eval 'for f (*) echo __ZSH__ "$f"'
fi
```


### Source here-document

This is the same as [Canina's answer](https://linux.codidact.com/posts/285278/285301#answer-285301). However, you can write the code in the same file by using here-document. 

```sh
if [ -n "$BASH_VERSION" ]; then
    for f in *; do echo __BASH__ "$f"; done
elif [ -n "$ZSH_VERSION" ]; then
    source /dev/stdin << '__ZSH_SRC__'
        for f (*) echo __ZSH__ "$f"
__ZSH_SRC__
fi
```