Skip to content

Instantly share code, notes, and snippets.

@KyonLi
Last active March 4, 2026 07:50
Show Gist options
  • Select an option

  • Save KyonLi/1b526ed77d7a1f285ce3304a1de400b4 to your computer and use it in GitHub Desktop.

Select an option

Save KyonLi/1b526ed77d7a1f285ce3304a1de400b4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# 将视频文件的URL推送到连接到本机的SSH客户端上的播放器
# 无参数时显示当前目录文件列表或直接推送唯一视频文件
# 也可以直接传入要播放的文件路径或序号
set -u # 未定义变量报错
file_exts='*.mp4 *.mov *.mkv'
url_prefix="http://user:passwrod@example.com"
# 推送到播放器
send() {
local abs_path="$1"
if [ -e "/share/${abs_path#*/*/*/}" ]; then
echo "播放文件:/share/${abs_path#*/*/*/}"
url="$url_prefix/$(echo -n "${abs_path#*/*/*/}" | jq -sRr @uri | sed 's/%2F/\//g')"
curl -fsSL -m 3 -X POST "http://${SSH_CONNECTION%% *}:9000/hooks/play" \
-H "Content-Type: application/json" \
-d "{\"url\":\"$url\"}"
else
echo "错误:转换文件路径失败" >&2
exit 1
fi
}
if [[ $# -eq 0 ]] || [[ $# -eq 1 && "$1" =~ ^[0-9]+$ ]]; then
# 没有参数或只有一个序号参数,查找当前目录所有视频文件
files=()
while IFS= read -r line || [[ -n "$line" ]]; do
files+=("$line")
done < <(ls -1 $file_exts 2>/dev/null || true)
#mapfile -t files < <(ls -1 $file_exts 2>/dev/null || true)
if [ ${#files[@]} -eq 0 ]; then
echo "当前目录没有找到任何有效文件" >&2
exit 1
fi
if [ $# -eq 1 ]; then
# 有序号参数
choice="$1"
fi
else
files=("$@")
fi
# 过滤不存在的文件
declare -a valid_files
declare -a display_names
i=1
for file in "${files[@]}"; do
if [ -f "$file" ]; then
# 转换为绝对路径并存储
abs_path=$(readlink -f "$file")
valid_files+=("$abs_path")
# 显示时尽量用相对路径更友好,但保留原样貌
display="$file"
# 如果路径很长,可以考虑只显示 basename,但这里保留原输入样子
display_names+=("$display")
((i++))
else
echo " !! 跳过(文件不存在): $file" >&2
fi
done
if [ ${#valid_files[@]} -eq 0 ]; then
echo "错误:没有任何有效文件" >&2
exit 1
fi
if [[ "${choice:-0}" -gt 0 && "${choice:-0}" -le ${#valid_files[@]} ]]; then
# 预选择了序号
send "${valid_files[((choice-1))]}"
exit
fi
if [ ${#valid_files[@]} -eq 1 ]; then
send "${valid_files[0]}"
exit
fi
# 让用户选择
echo "可选文件列表:"
echo "----------------------------------------"
i=1
for display in "${display_names[@]}"; do
printf " %2d) %s\n" "$i" "$display"
((i++))
done
while true; do
read -r -p "请选择文件序号 (1-${#valid_files[@]}): " choice
# 检查是否为数字
if [[ ! $choice =~ ^[0-9]+$ ]]; then
echo "请输入数字" >&2
continue
fi
# 检查范围
if (( choice < 1 || choice > ${#valid_files[@]} )); then
echo "序号超出范围 (有效范围:1-${#valid_files[@]})" >&2
continue
fi
# 发送到播放器
send "${valid_files[((choice-1))]}"
break
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment