至少在我的屏幕版本¹上,通过-X 向分离的会话发送命令不适用于可能更改当前窗口的内容(例如next 或select 0)。其他命令,例如 stuff,确实有效。也许这是一个错误,我不知道。我怀疑这是“设计使然”,因为 -Q select ... 标志也有同样的问题,如果可以的话,我希望它能解决这个确切的问题。
我对您提出的问题有进一步的解决方案,但我认为您可以像这样解决您的实际问题:
screen -S mysession -p 0 -X stuff 'some commands for your torrents'
在这里,我们不更改活动窗口,但我们使用 -p 选项将命令发送到特定窗口(在本例中为 0)。
另一个更厚脸皮的回答是“使用tmux——它对脚本有更好的支持”(:
¹ 版本 4.06.02 (GNU) 23-Oct-17
希望能解决您的问题,但我来到这里是因为我确实需要使用脚本更改屏幕会话中的活动窗口。
而且,在尝试解决您的问题时,我找到了我的解决方案,所以我会在此处添加,以防其他人感兴趣。
请注意,如果您通过某个终端手动连接,那么您可以在脚本中通过-X 发送next 和select 命令就可以了。但当然,我们不想手动附加;我们想自动化它。
所以...为可憎的事情做好准备(:
我们将使用单独的屏幕会话附加到我们关心的屏幕会话,从而将该会话置于“附加”状态,我们可以从主脚本向其发送select 命令。我们将从另一个脚本屏幕会话中编写屏幕脚本。
假设我们有一个名为foo 的现有会话,我们想向它发送select 0 命令。只运行这个不起作用:screen -S foo -X select 0。
相反,请执行以下操作:
#!/usr/bin/env bash
# (the only bash-ism here is $'\n', so you could do it with
# plain 'sh' easily, too)
# You could get this from a commandline argument, etc.
target_session=foo
# A unique name for our controller session. You could append a UUID
# if you might have two scripts running, but they would fight with
# each other anyway - probably best to avoid.
controller_session="control_$target_session"
# Create the controller session.
# It starts in detached state, so we can script against it.
screen -d -m -S "$controller_session" -t attacher
# The default window will be used for attaching to $target_session.
# We make a second window for running our "real" commands.
# We could also do this in a separate process or somesuch.
screen -S "$controller_session" -X screen -t runner
# Attach to the target session
# Note: if someone else was attached (eg: if you were watching), it
# will fail. But in that case, our subsequent command still have an
# attached session to work with, so our overall script will work.
screen -S "$controller_session" -p 0 -X stuff "screen -r '$target_session'"$'\n'
# Now that it's attached, we can run commands which change the active
# window. This is the real meat of this script, where we do the thing
# we care about.
screen -S "$controller_session" -p 1 -X stuff "screen -S '$target_session' -X select 0"$'\n'
# Hack!
# At least on my system, there needs to be some delay between the select
# command being run, and detaching. Otherwise, it does not take effect.
# 0.01 is too small, 0.05 seems to work, so this should be plenty.
sleep 0.1
# Detach from target_session
screen -S "$target_session" -X detach
# Kill the controller, since we're done with it.
screen -S "$controller_session" -X quit
它不漂亮,但我知道我会用它!