![](/img/trans.png)
[英]How to pass shell variables as Command Line Argument to a shell script
[英]How to pass argument to a shell command in shell script from terminal
我正在写一个 shell 脚本practice.sh
。 我想将我的第一个参数$1
从命令行提供给脚本中的ls
命令。例如,如果我在终端中运行我的脚本$bash practice.sh *.mp3
.mp3 我想用于ls
命令的参数*.mp3
#!/bin/bash
output=$ls $1
它没有任何帮助吗?
你说你想要什么的明显答案就是
#!/bin/bash
ls "$1"
它将运行ls
,将它(只是)第一个参数传递给脚本。
但是,您还说您想像这样运行: practice.sh *.mp3
运行带有许多arguments (不仅仅是一个)的脚本 - *.mp3
将扩展为所有 .mp3 文件中当前目录。 为此,您可能想要更多类似的东西
#!/bin/bash
ls "$@"
这会将所有arguments 传递给您的脚本(不管有多少)到ls
命令。
这些脚本将运行ls
,其标准输出连接到您的脚本的标准输出连接到的任何内容,因此 output 将(可能)只出现在您的终端上。 如果您想捕获ls
命令的 output (这样您就可以用它做其他事情),您需要类似
#!/bin/bash
output=$(ls "$@")
它将使用所有 arguments 运行ls
,并在变量$output
中捕获 output 。 然后,您可以使用该变量执行操作。
使用 shell 扩展将命令的 output 记录在变量output
:
output=$(ls $1)
这将在变量 output 中记录命令ls $1
的output
。 然后,您可以使用echo $output
打印出您的 output。
您可以在GNU Bash 参考手册中阅读有关 shell 扩展的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.