首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在调用变量内的命令时找不到

在调用变量内的命令时找不到
EN

Stack Overflow用户
提问于 2019-02-19 11:57:07
回答 2查看 70关注 0票数 1

我开始学习编程,并决定从shell开始。下面是我编写的使用scrot命令截图的脚本。

代码语言:javascript
复制
#!/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变量中的命令?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-19 12:05:39

如果要从scrot变量中使用scrotcmd,则必须执行以下操作

代码语言:javascript
复制
scrotcmd="scrot"

因为scrotcmd=$(scrot)执行scrot并将输出放入scrotcmd变量。

票数 0
EN

Stack Overflow用户

发布于 2019-02-19 12:05:53

我建议使用bash数组来处理任何未转义的奇怪字符串。

代码语言:javascript
复制
...
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")
...

你可以只使用字符串就可以逃脱,但这是不安全的,我建议你不要这么做:

代码语言:javascript
复制
...
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"
...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54765799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档