SKILL.md 3.69 KB

name: termux-su-execution description: Termux cron 中执行需要 /sdcard 访问的命令——su -c 包裹、su 环境限制(无bash/无~/无Termux PATH)。任何读写 /sdcard 的脚本/CLI 调用都需要此知识。 version: 1.0

category: android

Termux su -c 执行模式

何时需要

任何在 Termux cron 中访问 /sdcard 的操作都需要 su -c。Termux 进程没有 /sdcard 权限(文件属 media_rw group,Termux uid 不在组内)。

验证:

ls /sdcard/bosszhipin/
# → Permission denied

su -c 'ls /sdcard/bosszhipin/'
# → pull_dbs_local.sh  data/

su 环境三重限制

su -c 启动的是 /system/bin/sh,不是 Termux 的 bash。三个关键差异:

1. 无 bash — 用 sh 执行脚本

su -c "bash /sdcard/bosszhipin/pull_dbs_local.sh"  # → bash: inaccessible or not found
su -c "cd /sdcard/bosszhipin && sh pull_dbs_local.sh"  # ✓

如果脚本用 #!/usr/bin/env bash shebang,直接用 sh 仍然会 fallback 到 sh 解释器执行,通常可以工作。但如果脚本用了 bash-specific 语法(array、${var,,} 等),需要用全路径 bash:

su -c "/data/data/com.termux/files/usr/bin/bash /path/to/script.sh"

2. ~ 波浪号不展开 — 用全路径

/system/bin/sh 的 $HOME 指向 /:

su -c "python3 ~/script.py"
# → can't open file '//.script.py': No such file or directory

su -c "python3 /data/data/com.termux/files/home/script.py"  # ✓

Termux home 全路径:/data/data/com.termux/files/home

3. 无 Termux PATH — 用全路径二进制

su -c "python3 ..."   # → python3: inaccessible or not found
su -c "/data/data/com.termux/files/usr/bin/python3 ..."  # ✓

su -c "sqlite3 ..."   # → sqlite3: inaccessible or not found
su -c "/data/data/com.termux/files/usr/bin/sqlite3 ..."  # ✓

常用二进制全路径:

  • python3: /data/data/com.termux/files/usr/bin/python3
  • sqlite3: /data/data/com.termux/files/usr/bin/sqlite3
  • bash: /data/data/com.termux/files/usr/bin/bash

标准调用模板

# Python 脚本访问 /sdcard
su -c "/data/data/com.termux/files/usr/bin/python3 /data/data/com.termux/files/home/path/to/script.py --arg1 --arg2 2>&1"

# Shell 脚本(用 sh)
su -c "cd /path/to/script/dir && sh script.sh 2>&1"

# Shell 脚本(需要 bash)
su -c "/data/data/com.termux/files/usr/bin/bash /path/to/script.sh 2>&1"

# SQLite 查询
su -c "/data/data/com.termux/files/usr/bin/sqlite3 /sdcard/path/to/db.db 'SELECT ...' 2>&1"

常见错误速查

错误信息 原因 修复
Permission denied 访问 /sdcard Termux 无 /sdcard 权限 加 su -c
bash: inaccessible or not found su 环境无 bash 用 sh 或全路径 bash
python3: inaccessible or not found su 环境无 Termux PATH 用 /data/data/com.termux/files/usr/bin/python3
sqlite3: inaccessible or not found su 环境无 Termux PATH 用 /data/data/com.termux/files/usr/bin/sqlite3
can't open file '//.hermes/...' su 不展开 ~ 用 /data/data/com.termux/files/home/...

影响的所有管线

任何需要 /sdcard 读写的 cron job 都受影响:

  • BOSS 直聘简历管线(pull_dbs → extract → import → score → query)
  • 任何往 /sdcard 写输出文件的定时任务
  • 读取 /sdcard 下配置/数据的脚本

排查清单

遇到 cron job 命令失败时,检查:

  1. 命令是否访问了 /sdcard?→ 需要 su -c
  2. 是否用了 bash?→ 改成 sh 或全路径 bash
  3. 是否用了 ~ 路径?→ 改成全路径
  4. 是否用了裸 python3/sqlite3?→ 改成全路径
  5. 脚本是否用 dirname $0 获取自身目录?→ 需要 cd 到脚本目录