Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Arguments - Escape Spaces

Tags:

bash

arguments

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
like image 827
sidyll Avatar asked Jun 24 '11 16:06

sidyll


People also ask

What is $@ in bash?

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.

How do you assign a all the arguments to a single variable?

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.


2 Answers

Use this one:

./my_program "$*"
like image 53
Karoly Horvath Avatar answered Oct 08 '22 18:10

Karoly Horvath


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

like image 42
Konrad Kleine Avatar answered Oct 08 '22 17:10

Konrad Kleine