命令工作在交互的shell但不是shell脚本 [英] Command works in interactive shell but not shell script

查看:185
本文介绍了命令工作在交互的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中运行的精确相同的命令它。一切都使用绝对路径输出,所以我pretty很多在这里的损失。

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脚本:

The shell script:

#! /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天全站免登陆