Gopesh Bharadwaj
Gopesh Bharadwaj

Reputation: 160

How to check the current shell and change it to bash via script?

#!/bin/bash
 if [ ! -f readexportfile ]; then
    echo "readexportfile does not exist"
    exit 0
fi

The above is part of my script. When the current shell is /bin/csh my script fails with the following error:

If: Expression Syntax Then: Command not found

If I run bash and then run my script, it runs fine(as expected).

So the question is: If there is any way that myscript can change the current shell and then interpretate rest of the code.

PS: If i keep bash in my script, it changes the current shell and rest of the code in script doesn't get executed.

Upvotes: 0

Views: 1357

Answers (2)

pgl
pgl

Reputation: 7981

The other replies are correct, however, to answer your question, this should do the trick:

[[ $(basename $SHELL) = 'bash' ]] || exec /bin/bash

The exec builtin replaces the current shell with the given command (in this case, /bin/bash).

Upvotes: 1

Sriharsha Kalluru
Sriharsha Kalluru

Reputation: 1823

You can use SHEBANG(#!) to overcome your issue. In your code you are already using she-bang but make sure it is first and foremost line.

$ cat test.sh
#!/bin/bash
 if [ ! -f readexportfile ]; then
    echo "readexportfile does not exist"
    exit 0
 else
        echo "No File"
fi

$ ./test.sh
readexportfile does not exist

$ echo $SHELL
/bin/tcsh

In the above code even though I am using CSH that code executed as we mentioned shebang in the code. In case if there is no shebang then it will take the help of shell in which you are already logged in.

In you case you also check the location of bash interpreter using

$ which bash
or
$ cat /etc/shells |grep bash

Upvotes: 0

Related Questions