当我输入一个URL作为参数时,如何使bash脚本正常工作

时间:2012-01-21 03:38:13

标签: bash

我正在编写一个脚本,当脚本停止并在启动后立即转到后台时,我一直遇到问题。我很确定这是因为我输入后没有转义URL,但是我不确定如何制作它,所以一旦我输入它就会被转义。

我已粘贴下面的代码以及尝试运行时发生的情况。再一次,我真的需要帮助让URL在进入时正确逃脱。

#!/bin/bash
#

url=$1

if [ "$url" = "" ]; then

        echo "D: you did not supply a url!"
        exit

fi

echo "Please specify your preferred file format by entering the number corresponding to the format name below"
echo "1:avi 2:mp3 3:aac 4:best(program will pick the the best audio format available (aac, mp3, m4a, wav, vorbis))"

read format

if [ "$format" = "1" ]; then

        orders="-qt"

elif [ "$format" = "2" ]; then

        orders="-qt --extract-audio --audio-format mp3"

elif [ "$format" = "3" ]; then

        orders="-qt --extract-audio --audio-format aac"

elif [ "$format" = "4" ]; then

        orders="-qt --extract-audio --audio-format best"

else

        echo "You did not enter a valid option (1,2,3 or 4) :("
        exit

fi

echo "$orders" (debug stuff)

-------------------------------------------------------------------------------------------

以下是我运行脚本时会发生的事情:

austin@Ruby:~$ ./meddownload.sh http://www.youtube.com/watch?v=g34B-YOaC7c&ob=av2e

[1] 1001 austin @ Ruby:〜$请通过输入与下面的格式名称对应的数字来指定您的首选文件格式 1:avi 2:mp3 3:aac 4:最好(程序会选择最好的音频格式(aac,mp3,m4a,wav,vorbis)) 1     -bash:1:找不到命令

[1]+  Stopped                 ./meddownload.sh http://www.youtube.com/watch?v=g34B-YOaC7c

以下是当我输入非URL作为参数时发生的情况(这表明URL很可能是导致问题的原因):

austin@Ruby:~$ ./meddownload.sh iuniuniun
Please specify your preferred file format by entering the number corresponding to the format name below
1:avi 2:mp3 3:aac 4:best(program will pick the the best audio format available (aac, mp3, m4a, wav, vorbis))
1
-qt

4 个答案:

答案 0 :(得分:4)

必须引用网址http://www.youtube.com/watch?v=g34B-YOaC7c&ob=av2e,因为它包含&用途:

'http://www.youtube.com/watch?v=g34B-YOaC7c&ob=av2e'

答案 1 :(得分:2)

您的命令行

austin@Ruby:~$ ./meddownload.sh http://www.youtube.com/watch?v=g34B-YOaC7c&ob=av2e
bash将

视为两个独立的命令:

&终止的命令,将其发送到后台,然后进行简单的shell变量赋值。

输出的第一位,`[1] 1001,是shell通知您第一个命令已成功发送到后台运行。

在下一个提示符下,您将获得后台命令的输出:

Please specify your preferred file format by entering the number corresponding to the format name below
1:avi 2:mp3 3:aac 4:best(program will pick the the best audio format available (aac, mp3, m4a, wav, vorbis))

当您键入1进行选择时,您实际上并未将其发送到脚本中的read命令。因为它在后台运行,所以你真的在下一个提示符下键入1,这就是为什么bash认为你正在尝试运行程序1并回复

-bash: 1: command not found

最后,你的后台脚本已经到达了read命令,并且 - 当他们尝试从stdin读取时,后台进程执行 - 停止直到它返回到前台:

[1]+  Stopped                 ./meddownload.sh http://www.youtube.com/watch?v=g34B-YOaC7c

答案 2 :(得分:1)

看到了吗? g34B-YOaC7c&ob=av2e

shell正在拿起&符号并将命令放在后台。

使用单引号'

围绕网址

答案 3 :(得分:0)

在bash中& 向后台发送命令..导致你的错误。

引用网址修复