Cygwin Bash Scripts and Java

Running Java scripts in Cygwin bash scripts becomes a little tricky because you want to treat most paths in Cygwin as normal UNIX paths but Java expects DOS paths.  Therefore to get around this you can use the mixed option for cygpath.

For example:

if [ -e /usr/bin/cygpath ] || [ -e /bin/cygpath ]
then
  export FOO=`cygpath --mixed "e:\work\betweengo/target/foo"`
else
  export FOO="e:\work\betweengo/target/foo"
fi

The result on Cygwin is that FOO will be set to “e:/work/betweengo/target/foo” which will work both in DOS and UNIX.

Save the Output in a Shell Script Array

I wanted to do some shell processing on the contents of a directory. To do this I needed to put the contents of the directory in an array. Fortunately this is not difficult with bash.

  1. First capture the output.

    ls_output=$(ls /images)

  2. Next declare an array and reference the output with this array.

    declare -a img_files
    img_files=($ls_output)

  3. Now you can access the array directly or loop through it.

    echo ${img_files[0]}
    for img_file in ${img_files[@]}
    do
      ...
    done

Thanks O’Reilly’s Bash Cookbook.

Save the Output in a Shell Script Variable

I was counting how many times a file was referenced by other files. I then wanted to do some processing based on this number.

To do this I saved the output of this count in a variable which I was then able to reference later in the shell script.

num_files=`find . -type f -name '*.html' | xargs grep $img_file | wc -l`

# delete this file if it is not referenced
if [ "0" = $num_files ]
then
  rm $IMAGE_DIR/$img_file
fi