【发布时间】:2010-07-12 23:06:32
【问题描述】:
我正在尝试设置一个 shell 脚本,该脚本仅在从交互式 shell 调用时才会启动 screen 会话(或重新加入现有会话)。我看到的解决方案是检查$-是否包含字母“i”:
#!/bin/sh -e
echo "Testing interactivity..."
echo 'Current value of $- = '"$-"
if [ `echo \$- | grep -qs i` ]; then
echo interactive;
else
echo noninteractive;
fi
但是,这会失败,因为脚本是由一个新的非交互式 shell 运行的,它是由顶部的 #!/bin/sh 调用的。如果我获取脚本而不是运行它,它会按需要工作,但这是一个丑陋的 hack。我宁愿在我运行它时让它工作。
那么如何测试脚本中的交互性?
【问题讨论】:
-
我只想指出你的shebang说“sh”,但你的问题说“bash”。如果您希望脚本中包含 Bash 功能,则应将 shebang 设置为
#!/bin/bash(即使在您的系统上,sh符号链接到bash)。
标签: environment-variables interactive sh subshell