调用变量内scrot命令时提示“Command not found”的问题
问题分析与解决:Shell脚本中scrotcmd变量调用报错
哈哈,这个坑我刚学Shell的时候也踩过!让我给你掰扯清楚问题出在哪,以及怎么修复~
错误根源:你把「命令执行结果」当成「命令本身」存起来了
你写的scrotcmd=$(scrot)是命令替换语法,它会立刻执行scrot命令,然后把命令的标准输出内容赋值给scrotcmd变量。但scrot这个工具默认执行后,只会默默完成截图操作,不会往标准输出里输出任何内容——所以scrotcmd最后变成了空字符串!
当你后面执行"$scrotcmd" -q 90 ...的时候,就相当于在执行 -q 90 ...,Shell当然会报错「找不到命令」,因为命令的位置是空的呀!
修复方案:把命令本身存在变量里,而不是提前执行它
正确的做法是把scrotcmd作为命令模板来存储,而不是执行它。下面是修改后的完整脚本:
#!/bin/bash # Take a screenshot and save with date D=$(date +%Y%m%d) # grab the date SC_DIR=~/Pictures/Screenshots # save to this directory scrotcmd="scrot" # 直接存储命令字符串,不执行 # 提前创建截图目录,避免scrot因目录不存在报错 mkdir -p "$SC_DIR" # this function will check if the file exists and append a number in front of it. cheese() { if [[ -e "$SC_DIR"/scr-"$D".png ]] ; then i=1 while [[ -e "$SC_DIR"/scr-"$D"-"$i".png ]] ; do i=$((i+1)) done $scrotcmd -q 90 "$SC_DIR"/scr-"$D"-"$i".png else $scrotcmd -q 90 "$SC_DIR"/scr-"$D".png fi } case $1 in s) scrotcmd="scrot -s" # select a region for the screenshot cheese ;; w) scrotcmd="scrot -u -b" # focused window only cheese ;; *) scrotcmd="scrot" # entire screen cheese ;; esac
关键改动点说明:
- 变量赋值方式修改:把所有
scrotcmd=$(scrot ...)改成scrotcmd="scrot ...",这样变量里存的是完整的命令文本,而不是执行命令后的空输出。 - 新增目录创建逻辑:加了
mkdir -p "$SC_DIR",如果目标截图目录不存在,会自动创建它(包括父目录),避免scrot因为找不到存储路径而失败。 - (可选)更稳妥的数组方式:如果之后你的命令参数里有空格或者特殊字符,建议用数组存储命令,比如:
数组方式能更好地处理特殊参数,避免Shell解析错误。# 初始化数组 scrotcmd=(scrot) # 在case分支里修改数组 s) scrotcmd=(scrot -s) ;; # 执行时用数组展开 "${scrotcmd[@]}" -q 90 "$SC_DIR"/scr-"$D".png
内容的提问来源于stack exchange,提问作者user11002161
相关产品推荐
相关产品推荐

