Bash 中的字符串插值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/828824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String interpolation in Bash
提问by ByteNirvana
My code
我的代码
#!/bin/bash
for (( c=0; c<=1127; c++ ))
do
id = 9694 + c
if (id < 10000); then
wget http://myurl.de/source/image/08_05_27_0${id}.jpg
else
wget http://myurl.de/source/image/08_05_27_${id}.jpg
fi
done
I only get
我只得到
./get.sh: line 5: 10000: No such file or directory
--2009-05-06 11:20:36-- http://myurl.de/source/image/08_05_27_.jpg
without the number.
没有号码。
The corrected code:
更正后的代码:
#!/bin/bash
for (( c=0; c<=1127; c++ ))
do
id=$((9694+c))
if (id -lt 10000); then
wget http://myurl.de/source/image/08_05_27_0${id}.jpg
else
wget http://myurl.de/source/image/08_05_27_${id}.jpg
fi
done
And even better:
甚至更好:
for i in $(seq 9694 10821) ; do
_U=`printf "http://myurl.de/source/image/08_05_27_%05d.jpg" $i`
wget $_U
done
回答by greg
I'll opt for simpler solution
我会选择更简单的解决方案
for i in $(seq 9694 10821) ; do
_U=`printf "http://myurl.de/source/image/08_05_27_%05d.jpg" $i`
wget $_U
done
回答by Ville Laurikari
You are making a couple of mistakes with bash syntax, especially when dealing with arithmetic expressions.
您在使用 bash 语法时犯了几个错误,尤其是在处理算术表达式时。
- You cannot put a space around the = sign when assigning to a variable.
- In the assignment to "id", to invoke arithmetic evaluation, you need to use the $(( expression )) syntax.
- For the "if" condition, you need double parentheses just like you're using with "for".
- 分配给变量时,不能在 = 符号周围放置空格。
- 在对“id”的赋值中,要调用算术求值,您需要使用 $(( expression )) 语法。
- 对于“if”条件,您需要双括号,就像您使用“for”一样。
This should work:
这应该有效:
#!/bin/bash
for (( c=0; c<=1127; c++ )); do
id=$((9694 + c))
if ((id < 10000)); then
wget http://myurl.de/source/image/08_05_27_0${id}.jpg
else
wget http://myurl.de/source/image/08_05_27_${id}.jpg
fi
done
回答by paxdiablo
This is what you need.
这就是你所需要的。
#!/bin/bash
for (( c=0; c<=1127; c++ ))
do
((id = 9694 + c))
if [[ id -lt 10000 ]] ; then
wget http://myurl.de/source/image/08_05_27_0${id}.jpg
else
wget http://myurl.de/source/image/08_05_27_${id}.jpg
fi
done
回答by joeytwiddle
You need:
你需要:
id=$((9694+c))
...
if [[ id < 10000 ]]; then

