命令在交互式 shell 中有效,但在 shell 脚本中无效 [英] Command works in interactive shell but not shell script

查看:87
本文介绍了命令在交互式 shell 中有效,但在 shell 脚本中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,它可以为 javac 生成适当的参数来编译我的项目,以努力提高对 shell 脚本编写的熟练程度.

I wrote a script that would generate the appropriate arguments to javac to compile my project in an effort to grow more proficient at shell scripting.

奇怪的是.. 脚本运行良好,但如果脚本运行带有这些参数的 javac 它不起作用,如果我在交互式 shell 中运行 exact 相同的命令,它会起作用.一切都是用绝对路径输出的,所以我在这里几乎不知所措.

The weird this is.. The script works perfectly, but if the script runs javac with those parameters it doesn't work, and if I run the exact same command in the interactive shell it does. Everything is outputted with absolute paths, so I'm pretty much at a loss here.

示例目录结构:

src/File.java
src/File.png
src/dir/File2.java
jars/Library.jar

预期输出:

build/File.class
build/File.png
build/dir/File2.class

shell 脚本:

#! /bin/sh

cwd=$(pwd)

if [ -d "build" ]; then
    rm -rf $cwd/build/*
else
    mkdir $cwd/build
fi

find $cwd/src ( ! -path '*/.*' ) -type f ! -iname "*.java" | xargs -I{} cp --parents {} $cwd/build

cmd=$(echo javac -sourcepath $cwd/src -classpath $(find $cwd/jars -type f | awk '{ printf(""%s";", $0);}'  | awk '{ print substr($0, 0, length($0)); }') -d $cwd/build $(find $cwd/src ( ! -path '*/.*' ) -type f -iname "*.java"))

$cmd
echo $cmd

命令输出:

javac -sourcepath /home/test/src -classpath "/home/test/jars/Library.jar" -d /home/test/build /home/test/src/File.java /home/test/src/dir/File2.java

我的实际项目太大而无法在此处发布,但基本上发生的情况是我得到了大量错误输出,好像类路径设置不正确(它们是库函数上的错误).如果我从 echo 语句中复制命令,粘贴它,然后按回车键,它就可以完美运行.

My actual project is too large to post here, but basically what happens is I get a huge amount of error output, as if the classpath was improperly set (they're errors on library functions). If I copy the command from the echo statement, paste it, and hit enter it works perfectly.

我不明白.

有什么想法吗?

推荐答案

你在 -classpath 的参数两边加的引号是按字面处理的,因为它们是 值的一部分$cmd.在 $cmd 展开并将结果字符串解析为命令行后,它们不会被删除.就好像你在命令行中输入了

The quotation marks you put around the argument to -classpath are treated literally, because they are part of the value of $cmd. They are not removed after $cmd is expanded and the resulting string is parsed as a command line. It's as if you had typed at the command line

$ javac -sourcepath /home/test/src -classpath "/home/test/jars/Library.jar" -d /home/test/build /home/test/src/File.java /home/test/src/dir/File2.java

这篇关于命令在交互式 shell 中有效,但在 shell 脚本中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆