我开始学习编程,并决定从shell开始。 这是我编写的脚本,用于使用scrot命令获取屏幕截图。
#!/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)
# 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
当我运行它时,它给了我这个: scrot:第16行::找不到命令
为什么不在$ scrotcmd var中调用命令?
答案 0 :(得分:1)
如果您想使用scrot
变量中的scrotcmd
,则必须这样做
scrotcmd="scrot"
因为scrotcmd=$(scrot)
执行scrot
并将输出放入scrotcmd
变量。
答案 1 :(得分:1)
我建议使用bash数组来处理所有未转义的奇怪字符串
...
scrotcmd=(scrot)
...
cheese() {
...
# is properly expanded, as the input
# so the spaces and all unreadable characters are preserved as in the input
"${scrotcmd[@]}" -q 90 "$SC_DIR"/scr-"$D"-"$i".png
...
}
...
scrotcmd=(scrot -a -u "arg with spaces")
...
您可以只使用字符串,但是这是不安全的,我建议您不要使用它:
...
scrotcmd="scrot"
...
cheese() {
...
# this is unsafe
# the content of the variable $scrotcmd is reexpanded
# so arguments with spaces will not work as intended
# cause space will intepreted as command separator
$scrotcmd -q 90 "$SC_DIR"/scr-"$D"-"$i".png
...
}
...
scrotcmd="scrot -a"
...