Command works in interactive shell but not shell script

拈花ヽ惹草 提交于 2019-12-13 04:28:19

问题


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.

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.

Example directory structure:

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

Expected output:

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

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

Command output:

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

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.

I don't get it.

Any ideas?


回答1:


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



回答2:


In general, anytime you can cut-n-paste a command and make it work but the shell is not working when it is running that command, there is a quoting problem somewhere. Rather than trying to figure out what it is, just make the shell evaluate the string. In other words, instead of:

$cmd

you want the shell to evaluate $cmd as if you had typed it directly:

eval $cmd


来源:https://stackoverflow.com/questions/12360098/command-works-in-interactive-shell-but-not-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!