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.
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).
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With