我开始学习编程,并决定从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变量中的命令?
发布于 2019-02-19 12:05:39
如果要从scrot变量中使用scrotcmd,则必须执行以下操作
scrotcmd="scrot"因为scrotcmd=$(scrot)执行scrot并将输出放入scrotcmd变量。
发布于 2019-02-19 12:05:53
我建议使用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"
...https://stackoverflow.com/questions/54765799
复制相似问题