3

I read Can a Bash script tell what directory it's stored in?, it shows I can get script directory by DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )".

I find I can use cd command to change working directory.

This is the content of import.sh. It is in /Users/gqqnbig/SourceCode/Java/PlayerStatisticReader/bin.

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

cd DIR

java -cp .;jsoup-1.7.3.jar;mysql-connector-java-5.1.29-bin.jar globalVisionEntertainment.nba.Program %1

This is what I get after executing the script.

Macintosh:PlayerStatisticReader gqqnbig$ pwd
/Users/gqqnbig/SourceCode/Java/PlayerStatisticReader
Macintosh:PlayerStatisticReader gqqnbig$ bin/import.sh 
: command not found 2: 
: No such file or directoryDIR
: command not found 4: 

I execute it in the default terminal in Macintosh.

Why is the command not found? How can I make it work?

Community
  • 1
  • 1
Gqqnbig
  • 5,845
  • 10
  • 45
  • 86
  • 1
    Based on the error messages, it looks like `import.sh` uses DOS line endings. Be sure to save the file to use UNIX/OS X line endings instead. – chepner Mar 13 '14 at 19:33
  • You are correct. After applied Silly Freak's method, my script works. Besides, I have to change ; to : in the classpath option. – Gqqnbig Mar 13 '14 at 19:50
  • possible duplicate of [: command not foundop/dominio.sh: line 2:](http://stackoverflow.com/questions/21889410/command-not-foundop-dominio-sh-line-2) – tripleee Mar 14 '14 at 06:44

3 Answers3

4

use the following to expand the variable

cd ${DIR}
Amit
  • 19,780
  • 6
  • 46
  • 54
4

you need to write

cd "$DIR"

strictly, you only need to add the dollar, but you should also quote the path because it may contain spaces. as to the command not found messages; I don't know. You can remove the empty lines. my guess is it's an encoding issue. do you get the "command not found" output if you paste the script directly into your terminal instead of running the file?

Silly Freak
  • 4,061
  • 1
  • 36
  • 58
  • After I remove empty lines, and change to `cd "$DIR"`, I get `: No such file or directory/Users/gqqnbig/SourceCode/Java/PlayerStatisticReader/bin`. – Gqqnbig Mar 13 '14 at 19:25
0

For what it's worth, I was looking for a solution on how to schedule a command with specific work directory via crontab schedule.

I found a way to do it in one line with env.

env -C workdir - command args
Yuri Pozniak
  • 667
  • 7
  • 11