What's the purpose of -i and -s options of bash?

It seems that either I don’t understand what these options mean, or bash behaves the same (as interactive shell that reads standard input) without any options anyway. When would I want to use these options explicitly?

Asked By: Max Yankov

||

From what I can understand it seems to be used for testing purposes. A startup file can use this to test the state as well as a shell script.

By default when you invoke a bash shell, it uses -i and -s so I am assuming for testing purposes you can invoke the shell explicitly with these options via the script or file to test the state that a normal login bash shell would provide.

I found that information from the man page under invocation Esref stated in the comments. It may not be so easily understood though, as it doesnt seem to be something a person would do normally.

Answered By: dakka

A different way to look at Bash invocation

The reference manual has a pretty detailed description on how to invoke Bash. I prefer to document it slightly differently though:

bash <options> <script_file> [<arguments>]
bash <options> -c <command_string> [<arguments>]
bash <options> [-s [<arguments>]

The first two are non-interactive, and hence don’t have the associated features (prompt, job control, command history,…); However, if you need those features, you can enforce them with the -i flag.

The third one is interactive, and the optional -s flag is justified in the paragraphs below…

Specifying arguments

Example 1: Basic

The -s option can be used to specify arguments:

bash -s a b c

starts a shell… In this shell we can check arguments:

echo $1 $2 $2

reflects the arguments from the bash command:

a b c

Without the ‘-s’ option, the first positional argument would be interpreted as a file name:

bash a b c

gives

bash: a: No such file or directory

Example 2: Using a heredoc

The previous use of the -s option can be used to provide arguments to a heredoc (when you don’t want to use a file to embed the commands):

bash -s a b c <<'EOC'
echo $1 $2 $3
EOC

gives:

a b c

Note that the bash command executes the commands in the heredoc, and then exits; This brings you back to the shell where you invoked the bash command.


Example 3: Pipelining

Consider embedding bash in a pipeline (when you need to implement some inline scripting), again the opportunity to provide arguments can be exploited

echo 'echo HELLO $1' | bash -s WORLD

gives:

HELLO WORLD

This is a contrived example, but for some more complex scripting (with a heredoc!), this can come in handy…

Answered By: Flandraco
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.