Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the shell being used from Dash (or sh) to Bash during script execution?

Say there’s a script that makes use of a certain Bash feature, like arrays. But say that script is being run using sh on Ubuntu, which is Dash, a shell that does not support arrays. Let’s also assume I can’t control which shell is being used from the get go, i.e. I’m stuck with Dash to start the script with.

Is it possible to detect and switch away from Dash (or any other shell) to Bash, assuming the location of Bash binary is known and can be safely assumed to be consistent? E.g. I run the following script using sh myscript.sh:

#!/bin/sh

# Do something here to detect Dash and switch to Bash (/bin/bash)

my_array=(yay i can use arrays now)

# ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Bash always sets BASH_VERSION. You can check if it’s set and restart the script with bash otherwise like this:

if [ -z "$BASH_VERSION" ]; then
  exec bash "$0"
fi

my_array=(yay i can use arrays now)

# ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading