shell “bash -imyscript.sh“与“bash myscript.sh”之间有什么区别?

svmlkihl  于 2023-01-26  发布在  Shell
关注(0)|答案(1)|浏览(107)

根据bash手册页,它说-i是用于shell的交互模式。我尝试了示例代码来找出-i选项的作用。interactive.sh是需要用户输入的脚本,这意味着交互脚本。
默认的bash选项是非交互模式,但是interactive.sh在非交互模式下运行没有任何问题,在交互模式下也运行良好,这让我很困惑。
bash中-i选项的确切用法是什么?shell中交互模式和非交互模式的区别是什么?

$cat interactive.sh
#!/bin/bash
echo 'Your name ?'
read name
echo "Your name is $name"

$ bash interactive.sh
Your name ?
ABC
Your name is ABC

$ bash -i interactive.sh
Your name ?
DEF
Your name is DEF
92vpleto

92vpleto1#

使用bash -i script,您将运行交互式非登录shell。q
bash中-i选项的确切用法是什么?
man bash开始:

-i        If the -i option is present, the shell is interactive.

shell中交互模式和非交互模式的区别是什么?
有一些不同之处,请看man bash | grep -i -C5 interactive | less

An interactive shell is one started without non-option arguments (unless -s is specified) and without the -c option whose standard input and er‐
   ror  are  both  connected to terminals (as determined by isatty(3)), or one started with the -i option.  PS1 is set and $- includes i if bash is
   interactive, allowing a shell script or a startup file to test this state.

   When an interactive login shell exits, or a non-interactive login shell executes the exit builtin command, bash reads and executes commands from
   the file ~/.bash_logout, if it exists.

   When  an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists.  This may
   be inhibited by using the --norc option.  The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.

[...]

When bash is interactive, in the absence of any traps, it ignores SIGTERM (so that kill 0 does not kill an interactive  shell),  and  SIGINT  is
   caught  and handled (so that the wait builtin is interruptible).  In all cases, bash ignores SIGQUIT.  If job control is in effect, bash ignores
   SIGTTIN, SIGTTOU, and SIGTSTP.

例如bash -i -c 'echo $PS1'

相关问题