Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash scripting: build a command then execute

Tags:

bash

shell

I'm trying to make a function that basically takes in arguments like f hello there my friend and searches a directory using find for all occurences of any of those strings, so it would be find | grep 'hello\|there\|my\|friend'. I'm new to shell scripting, but my code is below:

function f { 
  cmd="find | grep '"
  for var in "$@"
  do 
    cmd="$cmd$var\\|"
  done
  cmd="${cmd%\\|}'"
  echo "$cmd"
  $cmd 
}

When I execute the command, I get this:

# f hello there my friend
find | grep 'hello\|there\|my\|friend'
find: `|': No such file or directory
find: `grep': No such file or directory
find: `\'hello\\|there\\|my\\|friend\'': No such file or directory

Why does it not work, and how can I make it work? I imagine it's something to do with the string not being converted to a command, but I don't know enough about how shell scripting works to figure it out.

like image 956
ewok Avatar asked Sep 25 '15 17:09

ewok


People also ask

What does $() mean bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


1 Answers

It looks like your command syntax is correct. To run the command from a script in bash and capture the result, use this syntax:

cmd_string="ls"
result=$($cmd_string)
echo $result
like image 132
miken32 Avatar answered Sep 17 '22 18:09

miken32