【发布时间】: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/bin或echo /usr/bin/*。