【问题标题】:Use letters a-z in a variable in for loop in Bash? [duplicate]在 Bash 的 for 循环中的变量中使用字母 a-z? [复制]
【发布时间】:2018-07-15 18:12:36
【问题描述】:

我找不到合适的方式来充分表达自己,因此如果我弄得一团糟,我深表歉意。

我的问题是:如何在 bash 的 for 循环中使用字母 a..z?

#Aim is to list commands are the directory /usr/bin
#!/bin/bash
cd /usr/bin
for i in {a..z}
array=($(ls --ignore=[!a]*)) #Just lists commands starting with "a"
echo ${array[@]}

#I tried to do a substitution in the below code, where may I be wrong?
#!/bin/bash
cd /usr/bin
for i in {a..z}
array=($(ls --ignore=[!$i]*))
echo ${array[@]}

【问题讨论】:

  • 你实际上是用 bash 运行这个脚本,而不是其他的 shell?请注意,shebang 行 (#!/bin/bash) 必须 是文件中的第一行,并且如果您使用 sh scriptname 运行脚本,它将忽略 shebang 并使用 sh 而不是 @987654326 @。此外,您的示例缺少 done,这将导致任何 shell 中的语法错误。而ls --ignore=[!$i]* 是获取以$i 开头的文件名列表的一种非常奇怪且容易出错的方法;只需设置shopt -s nullglob,然后使用array=("$i"*)
  • @GordonDavisson 没错。我不认为这个问题应该被标记为重复,这应该是答案:)
  • 要列出 /usr/bin 中的命令,只需执行 ls /usr/binecho /usr/bin/*

标签: arrays bash shell


【解决方案1】:

要遍历 az,请使用以下命令:

for x in {a..z}
do
    echo "$x"   # prints alphabet
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-15
    • 2020-09-12
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多