我有一个Bash脚本需要调用一个命令,该命令需要其中一个参数的引号.当我运行命令
myTimeCommand --time="2018 04 23 1100" -o /tmp/myOutput ~/myInput
Run Code Online (Sandbox Code Playgroud)
从命令行,它工作正常.在我的脚本中,我想传递"2018 04 23 1100"作为参数并将其直接发送到命令.
myScript --time="2018 04 23 1100"
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试这个时,我收到一条错误消息
""2018" is not a valid time.
Run Code Online (Sandbox Code Playgroud)
我正在使用getopt解析参数.这是我的剧本
OPTIONS=t:
LONGOPTIONS=time:
PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTIONS --name "$0" -- "$@")
echo ${PARSED}
# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"
# now enjoy the options in order and nicely split until we see --
while true; do
echo "option: ${1}"
case "$1" in
-t|--time)
timeBase="$2"
timeBase="--time=\"${timeBase}\""
shift 2
;;
--)
shift
break
;;
*)
echo "Programming error"
exit 3
;;
esac
done
echo ${timeBase}
myTimeCommand ${timeBase} -o /tmp/myOutput ~/myInput
Run Code Online (Sandbox Code Playgroud)
编辑:删除了该runCommand()功能.虽然这产生了一些好评,但减损了手头的问题 - 复制引用的参数以使用命令运行.
第二个例子:
文本文件(myTest.txt)用
I have a Bash script that needs to call a command that will require quotes for one of it's arguments. When I run the command
myTimeCommand --time="2018 04 23 1100" -o /tmp/myOutput ~/myInput
from the command line, it works fine. In my script, I want to pass "2018 04 23 1100" as a parameter and send it directly to the command.
Run Code Online (Sandbox Code Playgroud)
当我跑步时,grep "command line" myTest.txt我得到最后一行的命中(如预期的那样).当我修改脚本时
OPTIONS=s:
LONGOPTIONS=str:
PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTIONS --name "$0" -- "$@")
echo ${PARSED}
# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"
# now enjoy the options in order and nicely split until we see --
while true; do
echo "option: ${1}"
case "$1" in
-s|--str)
sStr="\"$2\""
shift 2
;;
--)
shift
break
;;
*)
echo "Programming error"
exit 3
;;
esac
done
echo "grep ${sStr} myTest.txt"
grep ${sStr} myTest.txt
Run Code Online (Sandbox Code Playgroud)
echo按预期显示命令,但实际的grep失败
-bash-4.2~>./extText --str="command line"
grep "command line" myTest.txt
grep: line": No such file or directory
Run Code Online (Sandbox Code Playgroud)
如何使用传入的参数调用grep(在本例中为"命令行")?
不要使用变量来运行命令!它们用于保存数据而不是功能.使用数组
cmdArray=()
cmdArray=( "myTimeCommand" "${timeBase}" "-o" "/tmp/myOutput" "~/myInput" )
Run Code Online (Sandbox Code Playgroud)
并传递引用的数组以防止分词
runCommand "${cmdArray[@]}"
Run Code Online (Sandbox Code Playgroud)
请参阅BashFAQ/050 - 我正在尝试将命令放在变量中,但复杂的情况总是会失败!
| 归档时间: |
|
| 查看次数: |
171 次 |
| 最近记录: |