我正在尝试使用可执行文件填充变量以便稍后调用。我知道以下是错误的,因为它正在测试返回值,但我不确定如何正确执行(为了便于查看而添加了包裹):
CHECKSEC=`which checksec 2>/dev/null` || `which checksec.sh 2>/dev/null` ||
`ls /usr/local/bin/checksec 2>/dev/null` || `ls /usr/local/bin/checksec.sh 2>/dev/null`
更准确地说,我知道我可以用一堆if
语句来做,但我试图避免它,因为它展开到大约4或8个块:
if [ -z "$CHECKSEC" ]; then
CHECKSEC=`which checksec 2>/dev/null`
fi
...
if [ -z "$CHECKSEC" ]; then
echo "Unable to locate checksec. If you have it, be sure its on PATH. If"
echo " you need it, you can download it from http://www.trapkit.de/tools/."
exit 1;
fi
是否可以链接命令来填充变量,就像我正在尝试的那样? (或者这就是“为什么你会这样做”?)
如果是这样,我如何链接命令,以便当变量不为空且未定义时[特定]处理停止?
答案 0 :(得分:2)
执行你似乎想要做的事情的蛮力方式是:
CHECKSEC=$(which checksec 2>/dev/null ||
which checksec.sh 2>/dev/null ||
ls /usr/local/bin/checksec 2>/dev/null ||
ls /usr/local/bin/checksec.sh 2>/dev/null
)
它不是特别优雅,但它应该做的工作。使用$(…)
代替反引号(`…`
)通常是一个好主意。很有诱惑力:
CHECKSEC=$( {which checksec || which checksec.sh ||
ls /usr/local/bin/checksec || ls /usr/local/bin/checksec.sh; } 2>/dev/null)
减少重定向的次数。它也很容易考虑:
CHECKSEC=$( { PATH=$PATH:/usr/local/bin; which checksec || which checksec.sh; } 2>/dev/null)
以便which
将/usr/local/bin
视为最后的手段。
答案 1 :(得分:1)
在$ PATH和/ usr / local / bin中查找“not_this”,“ls”和“nor_that”。
应该找到“ls”。
#!/bin/bash
locate_cmd()
{
which "$1" || ls /usr/local/bin/"$1" 2>/dev/null
}
c=`locate_cmd not_this` || c=`locate_cmd ls` || c=`locate_cmd nor_that` || echo nope
echo cmd=$c