Kes*_*Kes 1 bash variable-substitution
我在 Bash 脚本中有一个行列表,如下所示
if [ ! -z "$clone01" ]; then git clone "$clone01"; fi
if [ ! -z "$clone02" ]; then git clone "$clone02"; fi
if [ ! -z "$clone03" ]; then git clone "$clone03"; fi
# $clone01 .... through to ... $clone60
if [ ! -z "$clone60" ]; then git clone "$clone60"; fi
Run Code Online (Sandbox Code Playgroud)
当数字小于 10 时,变量末尾的前导零很重要。
我尝试了各种替换和循环等。这段代码非常重复,总共有 60 行。
如何动态创建此代码并使其成为我执行的脚本的一部分?解决这个问题的最佳方法是什么?
好吧,别这样,太丑了。要么将 URL 放在一个数组中并循环遍历它:
urls=( http://this.git http://that.git )
for url in "${urls[@]}" ; do
git clone "$url"
done
Run Code Online (Sandbox Code Playgroud)
或者将它们放在一个文件中,每行一个,然后循环读取这些行。在这里,像您一样保护空行可能很有用。我们也可以忽略#
以注释开头的行:
while read -r url ; do
if [ -z "$url" ] || [ "${url:0:1}" = "#" ]; then continue; fi
git clone "$url"
done < file.with.urls
Run Code Online (Sandbox Code Playgroud)
如果您也需要行计数器,则可以轻松添加算术扩展。