简体   繁体   English

如何从终端将参数传递给 shell 脚本中的 shell 命令

[英]How to pass argument to a shell command in shell script from terminal

i am writing a shell script practice.sh .我正在写一个 shell 脚本practice.sh I want to give my first argument $1 from command line to ls command in script.eg if I run my script in terminal $bash practice.sh *.mp3 the argument *.mp3 I want to use for ls command我想将我的第一个参数$1从命令行提供给脚本中的ls命令。例如,如果我在终端中运行我的脚本$bash practice.sh *.mp3 .mp3 我想用于ls命令的参数*.mp3

#!/bin/bash
output=$ls $1

it doesn't work any help?它没有任何帮助吗?

The obvious answer for what you say you want is just你说你想要什么的明显答案就是

#!/bin/bash
ls "$1"

which will run ls , passing it (just) the first argument to the script.它将运行ls ,将它(只是)第一个参数传递给脚本。

However, you also say you want to run this like: practice.sh *.mp3 which runs the script with many arguments (not just one) -- the *.mp3 will be expanded to be all the of the.mp3 files in the current directory.但是,您还说您想像这样运行: practice.sh *.mp3运行带有许多arguments (不仅仅是一个)的脚本 - *.mp3将扩展为所有 .mp3 文件中当前目录。 For that, you likely want something more like为此,您可能想要更多类似的东西

#!/bin/bash
ls "$@"

which will pass all of the arguments to your script (however many there are) to the ls command.这会将所有arguments 传递给您的脚本(不管有多少)到ls命令。

These scripts will just run ls with its stdout connected to whatever your script has its stdout connceted to, so the output will (likely) just appear on your terminal.这些脚本将运行ls ,其标准输出连接到您的脚本的标准输出连接到的任何内容,因此 output 将(可能)只出现在您的终端上。 If you instead want to capture the output of the ls command (so you can do something else with it), you need something like如果您想捕获ls命令的 output (这样您就可以用它做其他事情),您需要类似

#!/bin/bash
output=$(ls "$@")

which will run ls with all the arguments, and capture the output in the variable $output .它将使用所有 arguments 运行ls ,并在变量$output中捕获 output 。 You can then do things with that variable.然后,您可以使用该变量执行操作。

Use shell expansion to record the output of the command in the variable output :使用 shell 扩展将命令的 output 记录在变量output

output=$(ls $1)

This will record the output of the command ls $1 in the variable output .这将在变量 output 中记录命令ls $1output You can then use echo $output to print out your output.然后,您可以使用echo $output打印出您的 output。

You can read more about shell expansion in the GNU Bash reference manual .您可以在GNU Bash 参考手册中阅读有关 shell 扩展的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM