Skip to content
Advertisement

Run find command from a bash file

Hi people: I’m making a xfe script to take a given directory as source file, use zenity to get output dir and perform some operations, for example:

#!/bin/bash

OUTPUT_DIR=`zenity --file-selection --directory --filename="$1"`

if [ $? == 0 ]; then
    find . -maxdepth 1 -type f -name "*.wav" -exec bash -c 'oggenc -Q "$0" -q 3 "$OUTPUT_DIR/${0%.wav}.ogg"' {} ;
fi

When the script is invoked, oggenc is not executed…any ideas?

Solution: Based on answers bellow, this works as expected:

#!/usr/bin/sh

OUTPUT_DIR=$(zenity --file-selection --directory --filename="$1")

if [ $? = 0 ]; then
    export OUTPUT_DIR
    find "$1" -maxdepth 1 -type f -name "*.wav" -exec sh -c 'oggenc -Q "$0" -q 3 -o "${OUTPUT_DIR}/$(basename "${0/.wav/.ogg}")"' {} ;
fi
zenity --info --text="Done"

Advertisement

Answer

To make the variable $OUTPUT_DIR available to the child process, add one line:

OUTPUT_DIR=$(zenity --file-selection --directory --filename="$1")
if [ $? = 0 ]; then
    export OUTPUT_DIR
    find . -maxdepth 1 -type f -name "*.wav" -exec bash -c 'oggenc -Q "$0" -q 3 "$OUTPUT_DIR/${0%.wav}.ogg"' {} ;
fi

Or, slightly simpler:

if OUTPUT_DIR=$(zenity --file-selection --directory --filename="$1"); then
    export OUTPUT_DIR
    find . -maxdepth 1 -type f -name "*.wav" -exec bash -c 'oggenc -Q "$0" -q 3 "$OUTPUT_DIR/${0%.wav}.ogg"' {} ;
fi

Notes:

  1. The command 'oggenc -Q "$0" -q 3 "$OUTPUT_DIR/${0%.wav}.ogg"' appears in single-quotes. This means that the variables are not expanded by the parent shell. They are expanded by the child shell. To make it available to the child shell, a variable must be exported.

  2. [ $? == 0 ] works in bash but [ $? = 0 ] will also work and is more portable.

  3. Command substitution can be done with backticks and some old shells only accept backticks. For modern shells, however, the $(...) has the advantage of improved readability (some fonts don’t clearly distinguish back and normal quotes). Also $(...) can be nested in a clear and sensible way.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement