从bash文件运行find命令

嗨人民:我正在做一个xfe脚本采取给定的目录作为源文件,使用zenity来获得输出目录和执行一些操作,例如:

#!/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 

当脚本被调用,oggenc不执行…任何想法?

解决scheme :根据以下答案,这可以按预期工作:

 #!/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" 

要使变量$OUTPUT_DIR可用于子进程,请添加一行:

 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 

或者,稍微简单些:

 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 

笔记:

  1. 命令'oggenc -Q "$0" -q 3 "$OUTPUT_DIR/${0%.wav}.ogg"'出现在单引号中。 这意味着这些变量不会被父shell所扩展。 它们由子shell扩展。 要使其可用于子shell,必须导出一个变量。

  2. [ $? == 0 ] [ $? == 0 ]在bash中工作,但[ $? = 0 ] [ $? = 0 ]也将工作,更便携。

  3. 命令替换可以用反引号来完成,一些旧的shell只能接受反引号。 然而,对于现代shell而言, $(...)具有提高可读性的优点(某些字体不能清楚地区分后面的和正常的引号)。 另外$(...)可以嵌套在一个清晰明智的方式。

我宁愿使用while循环流水线。 你的代码可以用这种方法重写

 while IFS= read -r -d '' file; do oggenc -Q "${file}" -q 3 "${OUTPUT_DIR}/$(basename ${file/.wav/.ogg})" done < <(find . -maxdepth 1 -type f -name "*.wav" -print0) 

你的代码不工作的原因是单引号'禁止变量扩展,所以$OUTPUT_DIR不会扩展。

编辑

-print0IFS=一起使用,仅在\0上拆分find输出,而不是在文件名中的空格上拆分find输出。