bash - Passing a command as a variable to a function in Unix -
can pass command variable function? if yes, syntax?
my code looks like.
function1(){ in $1 echo $a done } function2(){ function1 "ls -lrt folder/name | grep 'foo' | grep 'bar'" }
but doesn't work. tried passing as:
function1 `ls -lrt folder/name | grep 'foo' | grep 'bar'`
but passes first value of command (and understand why happens).
does know syntax pass command function variable?
as indicated in comments, using $1
contain first parameter. instead, need use $@
.
from bash manual → 3.4.2 special parameters:
$@
($@) expands positional parameters, starting one. when expansion occurs within double quotes, each parameter expands separate word. is, "$@" equivalent "$1" "$2" …. if double-quoted expansion occurs within word, expansion of first parameter joined beginning part of original word, , expansion of last parameter joined last part of original word. when there no positional parameters, "$@" , $@ expand nothing (i.e., removed).
then ask
what if function1 takes multiple parameters? , command third parameter being passed, using $@ takes in unnecessary values. how take values $3 onwards?
for this, want use shift
:
$ cat myscript.sh #!/bin/bash shift 2 echo "$@" $ ./myscript.sh b c d c d
shift
shift [n]
shift positional parameters left n. positional parameters n+1 … $# renamed $1 … $#-n. parameters represented numbers $# $#-n+1 unset. n must non-negative number less or equal $#. if n 0 or greater $#, positional parameters not changed. if n not supplied, assumed 1. return status 0 unless n greater $# or less zero, non-zero otherwise.
Comments
Post a Comment