Is there any easy way to "join" the arguments passed to a script? I'd like something similar to $@
, but that passes the arguments at once.
For example, consider the following script:
$/bin/bash
./my_program $@
When called as
./script arg1 arg2 arg3
my_program
will receive the arguments as 3 separated arguments. What I want, is to pass all the arguments as one argument, joining them — separated by spaces, something like calling:
./my_program arg1\ arg2\ arg3
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
Assigning the arguments to a regular variable (as in args="$@" ) mashes all the arguments together like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc.
Use this one:
./my_program "$*"
I've had a pretty similar problem today and came up with code like this (includes sanity checks):
#!/bin/sh
# sanity checks
if [ $# -lt 2 ]; then
echo "USAGE : $0 PATTERN1 [[PATTERN2] [...]]";
echo "EXAMPLE: $0 TODO FIXME";
exit 1;
fi
NEEDLE=$(echo $* | sed -s "s/ /\\\|/g")
grep $NEEDLE . -r --color=auto
This little script lets you search for various words recursively in all files below the current directory. You can use sed to replace your " " (space) delimiter with whatever you like. I replace a space with an escaped pipe: " " -> "\|" The resulting string can be parsed by grep.
Usage
Search for the terms "TODO" and "FIXME":
./script.sh TODO FIXME
You might wonder: Why not simply call grep directly?
grep "TODO\|FIXME" . -r
The answer is that I wanted to do some post-processing with the results in a more advanced script. Therefore I needed be able to compress all passed arguments (patterns) into a single string. And thats the key part here.
Konrad
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