Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a command as an argument to bash script

Tags:

bash

How do I pass a command as an argument to a bash script? In the following script, I attempted to do that, but it's not working!

#! /bin/sh

if [ $# -ne 2 ]
then
    echo "Usage: $0 <dir> <command to execute>"
    exit 1;
fi;

while read line
do
    $($2) $line
done < $(ls $1);

echo "All Done"

A sample usage of this script would be

./myscript thisDir echo

Executing the call above ought to echo the name of all files in the thisDir directory.

like image 388
One Two Three Avatar asked Apr 01 '13 18:04

One Two Three


People also ask

How do you pass arguments to a shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

What is $# in shell script?

$# : This variable contains the number of arguments supplied to the script. $? : The exit status of the last command executed. Most commands return 0 if they were successful and 1 if they were unsuccessful. Comments in shell scripting start with # symbol.


1 Answers

your command "echo" command is "hidden" inside a sub-shell from its argments in $line.

I think I understand what your attempting in with $($2), but its probably overkill, unless this isn't the whole story, so

 while read line ; do
    $2 $line
 done < $(ls $1)

should work for your example with thisDir echo. If you really need the cmd-substitution and the subshell, then put you arguments so they can see each other:

   $($2 $line)

And as D.S. mentions, you might need eval before either of these.

IHTH

like image 89
shellter Avatar answered Oct 13 '22 14:10

shellter