【发布时间】:2017-08-02 07:56:34
【问题描述】:
我正在尝试获取一个 bash 脚本,该脚本可以为给定的参数生成 JSDoc,例如
./jsdoc.sh file.js another.js maybe-a-third.js
我陷入了如何将未知数量的参数传递给下一个 shell 命令的问题。
(另外,不知道如何检查参数是否存在,只有在不存在时才存在if [ -z ... ])
此代码最多可用于两个参数,但显然不是正确的方法...
#!/bin/bash
# would like to know how to do positive check
if [ -z "$1" ]
then echo no param
else
d=$PWD
cd ~/projects/jsdoc-toolkit/
# this bit is obviously not the right approach
if [ -z "$2" ]
then java -jar jsrun.jar app/run.js -a -t=templates/jsdoc/ $d/$1
else java -jar jsrun.jar app/run.js -a -t=templates/jsdoc/ $d/$1 $d/$2
fi
cp -R out/jsdoc $d
fi
任何其他关于我如何实现这一点的指针将不胜感激。
编辑:根据@skjaidev 的回答更新脚本 - 快乐的日子;)
#!/bin/bash
d=$PWD
for i in $*; do
params=" $params $d/$i"
done
if [ -n "$1" ]; then
cd ~/projects/jsdoc-toolkit/
java -jar jsrun.jar app/run.js -a -t=templates/jsdoc/ $params
cp -R out/jsdoc $d
fi
【问题讨论】:
-
使用
"$@"代替 '$*` 以确保安全。我也会使用if (( $# > 0 ))——“$#”是参数的数量。