Gau*_*av 1 bash shell scripting ubuntu
我不得不在不同的行上打印在 shell 脚本中解析的所有参数。我写了一个脚本
for i in 1 2 3 4 5
do
echo $i
done
Run Code Online (Sandbox Code Playgroud)
但这打印
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
即使我将参数解析为“10 20 30 40 50”
和互联网上的一个代码
for i
do
echo $i
done
Run Code Online (Sandbox Code Playgroud)
此代码正确打印参数。
有人可以解释一下为什么该代码有效但我的无效吗?
另外,我如何使用一个变量 ($i) 的值作为变量名来打印其他内容。喜欢
i=1
$($i)
Run Code Online (Sandbox Code Playgroud)
应该打印 $1 的值。
for i 相当于 for i in "$@"
从 Bash help for:
Run Code Online (Sandbox Code Playgroud)for: for NAME [in WORDS ... ] ; do COMMANDS; done Execute commands for each member in a list. The 'for' loop executes a sequence of commands for each member in a list of items. If 'in WORDS ...;' is not present, then 'in "$@"' is assumed. For each element in WORDS, NAME is set to that element, and the COMMANDS are executed.
如果
in WORDS ...;不存在,则in "$@"假定
如果要从变量中获取变量,请使用间接扩展:
set -- arg1 arg2 arg3 foo
for i in 3 4 1 2
do
echo "${!i}"
done
# Output: arg3 foo arg2 arg1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3446 次 |
| 最近记录: |