Bash脚本生成的命令在控制台上有效,但在脚本中无效

时间:2022-03-19 16:23:56

Following puzzle: I have written a bash script with the simple task of extracting picture-less mp3 from mp4 files. The idea of this first draft is to just use

下面的谜题:我编写了一个bash脚本,其中包括从mp4文件中提取无图片mp3的简单任务。这个初稿的想法就是使用

avconv -i input.mp4 output.mp3

which works fine on the console.

在控制台上工作正常。

#!/bin/bash
# "extract_mp3_from_mp4.sh test.mp4 test.mp3"

if [ $# == 0 ]; then
        echo -e "Extracts mp3 from mp4 video.\nUsage: $0 src_mp4 [target_mp3=src_mp4.mp3];"
        exit 0;
fi;

file_in=$1;
file_out=$2;
if [ -z $file_out ]; then file_out="${file_in}.mp3"; fi;

echo "Attempting to extract '${file_in}' to '${file_out}'";

cmd="avconv -i ${file_in} ${file_out};";
echo "Casting command: ${cmd}";

exit `$cmd`;

Consider the call

考虑一下电话

./extract_mp3_from_mp4.sh test.mp4 test.mp3

generating the command

生成命令

avconv -i test.mp4 test.mp3;

What baffles me is this: The command created by the script is absolutely valid. If I copy it from the output generated by the echo "Casting command: ..." right into the console the command works as expected. However when used in the script (exit $cmd) avconv returns

令我困惑的是:脚本创建的命令绝对有效。如果我将它从echo“Casting command:...”生成的输出中复制到控制台中,该命令将按预期工作。但是,当在脚本中使用时(退出$ cmd),avconv将返回

Unable to find a suitable output format for 'test.mp3;

How can that be?

怎么可能?

1 个解决方案

#1


The problem is the semicolon:

分号是问题:分号:

cmd="avconv -i ${file_in} ${file_out};";

should be

cmd="avconv -i ${file_in} ${file_out}";

I basically recommend NOT using semicolons in BASH scripts, as this happens quite often

我基本上建议不要在BASH脚本中使用分号,因为这种情况经常发生

#1


The problem is the semicolon:

分号是问题:分号:

cmd="avconv -i ${file_in} ${file_out};";

should be

cmd="avconv -i ${file_in} ${file_out}";

I basically recommend NOT using semicolons in BASH scripts, as this happens quite often

我基本上建议不要在BASH脚本中使用分号,因为这种情况经常发生