Home > Enterprise >  How to pass argument to a shell command in shell script from terminal
How to pass argument to a shell command in shell script from terminal

Time:12-23

i am writing a shell script practice.sh. I want to give my first argument $1 from command line to ls command in script.e.g if I run my script in terminal $bash practice.sh *.mp3 the argument *.mp3 I want to use for ls command

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

it doesn't work any help?

CodePudding user response:

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.

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. 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.

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. If you instead want to capture the output of the ls command (so you can do something else with it), you need something like

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

which will run ls with all the arguments, and capture the output in the variable $output. You can then do things with that variable.

CodePudding user response:

Use shell expansion to record the output of the command in the variable output:

output=$(ls $1)

This will record the output of the command ls $1 in the variable output. You can then use echo $output to print out your output.

You can read more about shell expansion in the GNU Bash reference manual.

  • Related