用空格打开循环 [英] Bash for loop with spaces

查看:121
本文介绍了用空格打开循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  COMMANDS ='ls /df〜du  - hs〜/ Devel /'
for $ in $ COMMANDS;做
echo $ i
完成

如果结果是: p>

  ls / 
df〜
du -hs〜/ Devel /

但我找不到空格的正确语法。

解决方案

  COMMANDS =(ls /df〜du -hs〜/ Devel /)
为$ {COMMANDS [ @]};做
echo$ i
完成

这使用一个数组来存储命令。此功能也可以在 ksh zsh 中使用,但不在 sh $ b $数组的行为就像$ @参数数组。在$ {ARRAY_NAME [@]}(引号很重要)上应用 for 项目相继。如果你省略了引号,它们将会一起被分散在你的 IFS 环境变量('\t''\ n'''默认)。 b $ b

I would like to do something like this:

COMMANDS='"ls /" "df ~" "du -hs ~/Devel/"'
for i in $COMMANDS; do
    echo $i
done

Where the result would be:

ls /
df ~
du -hs ~/Devel/

But I can't find the right syntax for the spaces.

解决方案

COMMANDS=("ls /" "df ~" "du -hs ~/Devel/")
for i in "${COMMANDS[@]}"; do 
  echo "$i"
done

This uses an array to store the commands. This feature is also available in ksh, zsh, but not in sh.

Arrays behave like the "$@" argument array. Applying a for loop on "${ARRAY_NAME[@]}" (the quotes are important) will give you each item in succession. If you omit the quotes, it'll all get smushed together and split on the separators present in your IFS environment variable ('\t', '\n' and ' ' by default).

这篇关于用空格打开循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆